Example:
This code
os.loadAPI'debug' --or dofile'debug'
debug.override()
local function c()
error('a')
end
local function b()
c()
end
local function a()
b()
end
gives, give or take the paths:(the * counts the nested calls to the error-ing function in a line)
That's it! The functions used are available in the debug table. See 'Mor'e Examples' for it.
You can, for instance, get only the traceback string without throwing an error using debug.traceback(),
and print text one page at a time using debug.step_print(text).
Code
pastebin get YWwLUUpk debug
or here: http://pastebin.com/YWwLUUpk
Mor'e advanced examples:
Spoiler
debug=dofile('debug')
function B()
print(debug.traceback())
os.pullEvent('key')
s=''
for i=1,100 do s=s..i..'\n' end
very_long_text=s
--will wait for user to press keys if the text is too big for the screen
debug.printError(very_long_text)
os.pullEvent('key')--wait
--all in one go:
function d()
error(debug.traceback('ups!'))
end
local ok,err=pcall(d)
if not ok then print(err) end
os.pullEvent('key')--wait
--with xpcall:
--this catches latent/runtime erros not caused by error() calls:
function e()
a=''..{}
end
local ok, err=xpcall(c,debug.traceback)
if not ok then debug.printError(err) end
os.pullEvent('key')--wait
--dev section
--however, this fails, but the shell still runs, right till a new function is created I suppose
--(don't rerun this test)
function c()
c()
end
local ok2, ok, err=pcall(xpcall(c,function(...) end))
if not ok2 then debug.printError(ok)
elseif not ok then debug.printError(err) end
--[[java vm overflows aren't caught by xpcall
xpcall does not destroys the stack before calling the handler function.
If the stack is already at max capacity, it won't even accept the handler?
Who knows...
]]
end
function A()
B()
endA()
External functions used: Kingdaroo's wrap text function, found somewhere. Thanks.
Changelog:
?-separated traceback from error function.
?-file extracts
24/03/13 - toerror function for pcall produced errors (only one level of trace depth).
09/04/13 - now an api, overrides are optional, xpcall is great for catching errors not throwed by error(), but java vm overflows are not catched by it. pcall seems to do fine, but won't get the traceback. My opinion? xpcall, for tracebacks in almost all ocasions.
Future:
Special shell that opens/closes editor based on the error line automatically?
Dev:
xpcall(function() local f,e=loadstring('1\n1') end,print) prints an error message, but returns true. I.e., the error handler is called, but the execution of the function continues.