debug.setconstant
Replaces a constant in a function's constant table.
function debug.setconstant(func: function | number, index: number, value: any): ()Synopsis
How it works
Writes a new value into a Luau closureClosureA function value that captures its lexical environment. In Luau, closures come in two types: LClosure (Luau bytecode + Proto + upvalues) and CClosure (native C function pointer + upvalues).’s
Proto.k[] constant tableConstant tableThe Proto.k[] array containing all literal values (strings, numbers, booleans, nil) referenced by a function's bytecode. Instructions like LOADK and GETGLOBAL index into this table. at the specified index. Since the Proto is shared across all closures created from it, this change affects every closure instantiated from that prototype, not just the one you passed.Shared Proto implication
The
Proto is a shared object — when the CLOSURE opcode creates a new LClosure, it stores a pointer to the same Proto, not a copy. Patching k[i] on one closureClosureA function value that captures its lexical environment. In Luau, closures come in two types: LClosure (Luau bytecode + Proto + upvalues) and CClosure (native C function pointer + upvalues). changes the value seen by all sibling closures. This is both powerful (one patch affects all call sites) and dangerous (may break unrelated code paths that share the proto).
-- Both closures share the same Proto:
local a = function() print("hello") end
local b = function() print("hello") end
-- If they compile to the same proto,
-- patching one's constant patches both.Type constraint
The new value must be of a type valid in the constant tableConstant tableThe Proto.k[] array containing all literal values (strings, numbers, booleans, nil) referenced by a function's bytecode. Instructions like LOADK and GETGLOBAL index into this table.:
nil, boolean, number, or string. The Luau VMLuau VMThe Luau Virtual Machine — a register-based bytecode interpreter. Executes compiled Luau instructions sequentially, managing a value stack, call stack, and upvalue chains. Roblox runs one VM per Actor context. does not type-check constant loads at runtime, but mismatched types can cause crashes if bytecodeBytecodeThe compiled binary representation of Luau source code. A sequence of 32-bit instructions (opcodes + operands) stored in a Proto's code[] array. Executed by the Luau VM interpreter. instructions assume a specific type (e.g., CONCAT expects a string).Usage
Patch a string constant
local function foo()
print("Goodbye, world!")
end
debug.setconstant(foo, 3, "Hello, world!")
foo() "cc">--> Hello, world!Parameters
func function | number A Luau function or stack level.
index number Constant index to replace.
value any New value (must match type of existing constant).