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)
* 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
### `rolling-68`

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

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