Get Lua runtime error in the script

I don’t know how to debug scripts effectively. I need stack output like Python, but Lua/C doesn’t have this by default. I don’t know how to enable it. Or simply put , How to get the error output from the script?
You may be looking for a combination of xpcall and debug.traceback. You can use xpcall to pass the error handler to it and Use debug.traceback to get the stack trace:

function functionThatMayFail()
error('Failed')
end
local success, result = xpcall(functionThatMayFail,
function(err) return debug.traceback(err) end)
print(success, result)

This code will print:

false xpcall.lua:2: Failed
stack traceback:
xpcall.lua:6: in function
[ C]: in function'error'
xpcall.lua:2: in function
[C]: in function'xpcall'
xpcall.lua:5: in main chunk
[C]: ?

I don’t know how to debug scripts effectively. I need stack output like Python, but Lua by default /C doesn’t have this. I don’t know how to enable it. Or simply, how to get error output from the script?

You may be looking for a combination of xpcall and debug.traceback. You can use xpcall to pass the error handler to it and use debug.traceback to get the stack trace:

function functionThatMayFail()
error('Failed')
end
local success, result = xpcall(functionThatMayFail,
function(err) return debug.traceback(err) end)
print(success, result)

This code will print:

false xpcall.lua:2: Failed
stack traceback:
xpcall.lua:6: in function
[C]: in function'error'
xpcall.lua:2: in function
[C]: in function'xpcall'
xpcall.lua:5: in main chunk
[C]:?

Leave a Comment

Your email address will not be published.