ekd123
ekd123

Reputation: 535

Get Lua runtime errors inside the script

I have no idea how to debug scripts efficiently. I need a stack output like Python's but by default Lua/C doesn't have this. I don't know how to enable that. Or simply, how to get the error output from the script?

Upvotes: 4

Views: 3927

Answers (2)

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

You are probably looking for a combination of xpcall and debug.traceback. You can use xpcall to pass it an error handler and the 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 <xpcall.lua:6>
    [C]: in function 'error'
    xpcall.lua:2: in function <xpcall.lua:1>
    [C]: in function 'xpcall'
    xpcall.lua:5: in main chunk
    [C]: ?

Upvotes: 6

Telemachus
Telemachus

Reputation: 19705

The Lua interpreter does produce error output by default. E.g. (I introduced a typo into this script):

$ lua random.lua 
lua: random.lua:6: attempt to call global 'xists' (a nil value)
stack traceback:
    random.lua:6: in main chunk
    [C]: ?

Can you clarify what you're trying to do or maybe better what isn't happening that you expected to happen, in terms of error output?

Upvotes: 0

Related Questions