Add debug module

This commit is contained in:
Lars Mueller 2021-05-04 16:18:46 +02:00
parent c3f1cf8af9
commit e28ee76d7d
3 changed files with 55 additions and 33 deletions

@ -222,6 +222,18 @@ This is best left explicit. First, you shouldn't be using numbered field keys if
4. [`json`](https://json.org) 4. [`json`](https://json.org)
* Not recommended * Not recommended
## `debug`
`modlib.debug` offers utilities dumping program state in tables.
### `variables(stacklevel)`
Dumps local variables, upvalues and the function environment of the function at the given stacklevel (default `1`).
### `stack(stacklevel)`
Dumps function info & variables for all functions in stack, starting with stacklevel (default `1`).
## Release Notes ## Release Notes
### `rolling-68` ### `rolling-68`

@ -1,34 +1,43 @@
local function gather_info() function variables(stacklevel)
local locals = {} stacklevel = (stacklevel or 1) + 1
local index = 1 local locals = {}
while true do local index = 1
local name, value = debug.getlocal(2, index) while true do
if not name then break end local name, value = debug.getlocal(stacklevel, index)
table.insert(locals, {name, value}) if not name then break end
index = index + 1 table.insert(locals, {name, value})
end index = index + 1
local upvalues = {} end
local func = debug.getinfo(2).func local upvalues = {}
local envs = getfenv(func) local func = debug.getinfo(stacklevel).func
index = 1 local fenv = getfenv(func)
while true do index = 1
local name, value = debug.getupvalue(func, index) while true do
if not name then break end local name, value = debug.getupvalue(func, index)
table.insert(upvalues, {name, value}) if not name then break end
index = index + 1 table.insert(upvalues, {name, value})
end index = index + 1
return { end
locals = locals, return {
upvalues = upvalues, locals = locals,
[envs == _G and "globals" or "envs"] = envs upvalues = upvalues,
} fenv = fenv,
fenv_global = fenv == _G
}
end end
local c = 3 function stack(stacklevel)
function test() stacklevel = (stacklevel or 1) + 1
local a = 1 local stack = {}
b = 2 while true do
error(gather_info().upvalues[1][1]) local info = debug.getinfo(stacklevel, "nfSlu")
end if not info then
break
test() end
info.func = tostring(info.func)
info.variables = variables(level)
stack[stacklevel - 1] = info
stacklevel = stacklevel + 1
end
return stack
end

@ -53,7 +53,8 @@ for _, file in pairs{
"binary", "binary",
"b3d", "b3d",
"bluon", "bluon",
"persistence" "persistence",
"debug"
} do } do
modules[file] = file modules[file] = file
end end