Skip to content

Instantly share code, notes, and snippets.

@Fingercomp Fingercomp/stacktrace.lua
Last active Dec 16, 2018

Embed
What would you like to do?
A simple stacktracer for lua.
local function insertNonNil(t, v)
if v then
v = tostring(v)
if #v > 0 then
table.insert(t, v)
end
end
end
local function traceback(c)
for level = 0, math.huge do
local info = debug.getinfo(c, level, "ufnSl")
if not info then
break
end
local funcType, name, args, exec, defined = {}, nil, {}, "", {}
insertNonNil(funcType, info.what)
insertNonNil(funcType, info.namewhat)
table.insert(funcType, "function")
name = info.name or "<anon>"
if info.nparams then
for an = 1, info.nparams do
local argName, argValue = debug.getlocal(c, level, an)
if argValue ~= nil then
argName = argName .. "=" .. tostring(argValue)
end
table.insert(args, argName)
end
end
if info.isvararg then
table.insert(args, "...")
end
if info.currentline and info.currentline ~= -1 then
exec = ":" .. tostring(info.currentline)
end
insertNonNil(defined, info.short_src)
if info.linedefined and info.linedefined ~= -1 then
table.insert(defined, info.linedefined)
end
funcType = table.concat(funcType, " ")
args = table.concat(args, ", ")
defined = (defined[1] and (" in " .. defined[1] .. "") or "") ..
(defined[2] and (" at L" .. defined[2]) or "")
-- local Lua function <anon>(a, b, c, ...):33 (defined in blah.lua at 33)
local line = ("#%2d: %s %s%s%s%s"):format(
level,
funcType,
name,
#args > 0 and ("(" .. args .. ")") or "",
exec,
#defined > 0 and (" (defined" .. defined .. ")") or ""
)
print(line)
end
end
local c = coroutine.create(function()
local function outer(f, g, a, b)
g("outer", a, b)
f(g, a, b)
end
local function inner(f, a, b, ...)
coroutine.yield()
f("inner", a, b)
end
outer(inner, print, 42, 24)
end)
coroutine.resume(c)
traceback(c)
coroutine.resume(c)
-- stdout:
--> outer 42 24
--> # 0: C field function yield(...) (defined in [C])
--> # 1: Lua local function f(f=function: 0x55bea5785ef0, a=42, b=24, ...):79 (defined in trace.lua at L78)
--> # 2: Lua local function outer(f=function: 0x55bea608c900, g=function: 0x55bea5785ef0, a=42, b=24):75 (defined in trace.lua at L73)
--> # 3: Lua function <anon>:83 (defined in trace.lua at L72)
--> inner 42 24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.