Lesson 01 of 05
Debug Library — Introspection
Use the debug library to inspect functions, upvalues, and stack traces.
The debug library provides runtime introspection tools for analyzing code at runtime.
Stack inspection:
- debug.traceback() — generates a formatted stack trace string
- debug.info(level, flags) — gets info about a function at call stack level
- debug.info(func, flags) — gets info about a specific function
Flags for debug.info: "n" name, "l" line, "s" source, "f" func itself
Upvalue access:
- debug.getupvalues(func) — returns table of {name, value} for all upvalues
- debug.setupvalue(func, index, value) — modify an upvalue by index
Upvalues are the outer local variables captured by a closure — debug can read and modify them.
Constants:
- debug.getconstants(func) — returns all constants (strings, numbers) used in function bytecode
Local variable access:
- debug.getlocal(level, index) — read local variable from a stack frame
- debug.setlocal(level, index, value) — modify it
Note: Many debug functions are restricted or removed in standard Roblox scripts. Full access requires an executor environment.
luau
1-- Stack trace for error handling
2local function deepFunction()
3 error("Something went wrong")
4end
5
6local function middleFunction()
7 deepFunction()
8end
9
10local ok, err = pcall(function()
11 middleFunction()
12end)
13
14if not ok then
15 -- Get full stack trace
16 local trace = debug.traceback()
17 print("Error:", err)
18 print("Stack trace:\n", trace)
19end
20
21-- debug.info usage
22local function myFunc()
23 local info = debug.info(1, "nls") -- name, line, source
24 print("Function:", info.name)
25 print("Line:", info.currentline)
26 print("Source:", info.source)
27end
28myFunc()
29
30-- Upvalue inspection (executor environment)
31-- local function secret()
32-- local hidden = "private data" -- upvalue
33-- return function()
34-- return hidden -- captures hidden
35-- end
36-- end
37-- local closure = secret()
38-- local upvalues = debug.getupvalues(closure)
39-- print(upvalues[1].name, upvalues[1].value) -- "hidden" "private data"
40-- debug.setupvalue(closure, 1, "modified") -- change upvalue
READY · 40 lines
