Skip to content

Home › Cookbook

Precompiled Bytecode ​

Compiling once on a server or build step and shipping binary bytecode avoids repeating lexing, parsing, and O2 optimization at runtime. Because Ouro loads submodules lazily, executing precompiled bytecode through Ouro.VM.loadBytecode or sandbox:load(bytecode, { mode = "binary" }) never loads Ouro.Compiler or the parser.

Compile, Verify, and Execute ​

luau
--!strict
local Ouro = require("./ouro")

-- Build / server step: compile once at O2
local bytecode, compileErr = Ouro.compile([[
	local items = ...
	local total = 0
	for _, n in items do
		total += n
	end
	return total
]], {
	optimizationLevel = 2,
	debugLevel = 1,
})
assert(bytecode ~= nil, compileErr)

-- Verification gate before storing or shipping untrusted bytecode
local valid, verifyErr = Ouro.Bytecode.verify(bytecode)
assert(valid, verifyErr)

-- Runtime step: execute inside a budgeted sandbox with explicit mode = "binary"
local sb = Ouro.sandbox({ preset = "strict" })
local fn, loadErr = sb:load(bytecode, {
	name = "=sum_items",
	mode = "binary",
})
assert(fn ~= nil, loadErr)
assert(fn({ 10, 20, 12 }) == 42)

Fast Unguarded Execution via VM.loadBytecode ​

For trusted precompiled bytecode, call Ouro.VM.loadBytecode directly. It accepts a binary string or buffer, verifies the module, and runs on the unguarded @native dispatch loop unless limits or hooks are configured:

luau
--!strict
local Ouro = require("./ouro")

local bytecode = assert(Ouro.compile("local x = ...; return x * x", {
	optimizationLevel = 2,
}))

local square, err = Ouro.VM.loadBytecode(bytecode, {
	name = "=square",
})
assert(square ~= nil, err)
assert(square(9) == 81)

Storing Bytecode in a buffer ​

buffer inputs always load as binary bytecode (mode = "binary" by default) without ambiguity against text source:

luau
--!strict
local Ouro = require("./ouro")

local raw = assert(Ouro.compile("return 'ok'"))
local buf = buffer.fromstring(raw)

local ok, value = Ouro.run(buf, { preset = "strict" })
assert(ok and value == "ok")

Custom Opcode Encoding ​

When interoperating with custom wire encodings, pass matching encoder and decoder functions across compile, Bytecode.verify, Bytecode.deserialize, and loadBytecode / sandbox:load:

luau
--!strict
local Ouro = require("./ouro")

local function xorOp(op: number): number
	return bit32.bxor(op, 0x3C)
end

local encoded = assert(Ouro.compile("return 21 * 2", { encoder = xorOp }))
local okVerify, verifyErr = Ouro.Bytecode.verify(encoded, xorOp)
assert(okVerify, verifyErr)

local fn = assert(Ouro.VM.loadBytecode(encoded, { decoder = xorOp }))
assert(fn() == 42)