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,15 +1,16 @@
local function gather_info() function variables(stacklevel)
stacklevel = (stacklevel or 1) + 1
local locals = {} local locals = {}
local index = 1 local index = 1
while true do while true do
local name, value = debug.getlocal(2, index) local name, value = debug.getlocal(stacklevel, index)
if not name then break end if not name then break end
table.insert(locals, {name, value}) table.insert(locals, {name, value})
index = index + 1 index = index + 1
end end
local upvalues = {} local upvalues = {}
local func = debug.getinfo(2).func local func = debug.getinfo(stacklevel).func
local envs = getfenv(func) local fenv = getfenv(func)
index = 1 index = 1
while true do while true do
local name, value = debug.getupvalue(func, index) local name, value = debug.getupvalue(func, index)
@ -20,15 +21,23 @@ local function gather_info()
return { return {
locals = locals, locals = locals,
upvalues = upvalues, upvalues = upvalues,
[envs == _G and "globals" or "envs"] = envs 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")
if not info then
break
end
info.func = tostring(info.func)
info.variables = variables(level)
stack[stacklevel - 1] = info
stacklevel = stacklevel + 1
end
return stack
end end
test()

@ -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