lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello there,

I think I found an issue in the way Lua handles errors and tracebacks, so I have decided to share it here.

The problem is as follows: in some situations (sandboxes or testing libs, for example), it is useful to catch an error, do some operations and then raise it again. When doing so, it is very useful to provide the traceback of the original error.

If the error is initially captured with pcall, then its traceback is simply lost. If it's captured with xpcall, then its traceback can be stored as a string.

The problem is: what to do then?

If the error is a string, then one possibility is simply concatenating the error and its traceback, and raising that - error(msg .. traceback). That is more or less equivalent to bubbling it up.

On the other hand, if msg is something different, like a table or a number, it must be severely transformed if we want to conserve the traceback. I came out with these two options:

    error({msg = msg, traceback = traceback})
    error(tostring(msg) .. traceback)

This is not very satisfying, since the semantics of the message must be altered significantly.

I see this as a flaw in the language, but maybe it's just a flaw in my understanding.

I (reluctantly) propose this solution: make error accept a second optional parameter, called traceback, and use it [instead of / appended to] the error traceback. In other words, this:

    error(msg, traceback)

If changing error's params is too extreme, then I would settle for an additional function:

    xperror(msg, traceback)

Bonus points: it seems xpcall(f, err) is mostly used to get the error traceback. Unfortunately right now that requires the usage of the debug library. May I propose that the err function defaults to (an equivalent of) this:

    function(msg) return msg, debug.traceback() end

That way we could use xpcall as follows:

    local ok, result, traceback = xpcall(f) --> no second param use default --> return traceback

That's all. Thank you so much for Lua, it's great.

Enrique García (@otikik)
Barcelona, Spain