Debug

Runtime introspection of Luau functions: read and write constants, upvalues, protos, and stack entries; query debug metadata.

Overview

Luau functions hold more than just their code: the constants they use, the upvalues they captured, and protos for any functions defined inside them. This library can read all three and write most of them.

It's how you change stuff you can't get to any other way, like a hardcoded number inside a closure or a flag that got captured as an upvalue before you loaded.

Reading and editing a closure
local function example()
    local threshold = 100
    return function()
        return threshold * 2
    end
end

local inner = example()

-- Read what it closed over, then change it.
for i, value in pairs(debug.getupvalues(inner)) do
    print(i, value)              --> 1  100
end
debug.setupvalue(inner, 1, 5)
print(inner())                   --> 10

-- Constants live separately from upvalues.
print(debug.getconstants(example))

Be careful writing here

debug.setconstant and debug.setstack write straight into the VM. A wrong index or type won't give you a nice error, it'll usually just crash the game. Read the value first before you overwrite it.

Stack inspection

Constants

Upvalues

Protos

A proto is the compiled version of a function defined inside another function. debug.getprotos lists them, so you can get to a nested function that was never stored anywhere you can reach.

Registry & metatables

The Luau registry holds references the VM keeps alive itself. Use it as a last resort when nothing else gives you the object you want.