The basic problem is (roughly) that pcall must unwind the stack so that your error handling code is reached. This gives two obvious ways to tackle the problem: Create the stack trace before unwinding, or move the (potentially) error-throwing code out of the way, so the stack frames don't have to be removed.
The first is handled by xpcall. This sets an error handler that can create a message while the stack is still intact. (Note that there are some situations where xpcall will not call the handler,1 so it's not suitable for cleanup code! But for stack traces, it's generally good enough.)
The second option (this works always2) is to preserve the stack by moving the code to a different coroutine. Instead of
local ok, r1, r2, etc = pcall( f, ... )
do
local co = coroutine.create( f )
local ok, r1, r2, etc = coroutine.resume( f, ... )
and now the stack (in co) is still preserved and can be queried by debug.traceback( co ) or other debug functions.
If you want the full stack trace, you'll then have to collect both the stack trace inside the coroutine and the stack trace outside of it (where you currently are) and then combine both while dropping the first line of the latter:
local full_tb = debug.traceback( co )
.. debug.traceback( ):sub( 17 ) -- drop 'stack traceback:' line
1 One situation in which the handler isn't called is for OOMs:
g = ("a"):rep( 1024*1024*1024 ) -- a gigabyte of 'a's
-- fail() tries to create a 32GB string – make it larger if that doesn't OOM
fail = load( "return "..("g"):rep( 32, ".." ), "(replicator)" )
-- plain call errors without traceback
fail()
--> not enough memory
-- xpcall does not call the handler either:
xpcall( fail, function(...) print( "handler:", ... ) return ... end, "foo" )
--> false not enough memory
-- (for comparison: here, the handler is called)
xpcall( error, function(...) print( "handler:", ... ) return ... end, "foo" )
--> handler: foo
-- false foo
-- coroutine preserves the stack anyway:
do
local co = coroutine.create( fail )
print( "result:", coroutine.resume( fail ) )
print( debug.traceback( co ) .. debug.traceback( ):sub( 17 ) )
end
--> result: false not enough memory
--> stack traceback:
-- [string "(replicator)"]:1: in function 'fail'
-- stdin:4: in main chunk
-- [C]: in ?
2 Well, at least as long as Lua itself doesn't crash.