Niccolo M.
Niccolo M.

Reputation: 3413

How to show correct function names in error messages?

Let's say that I call some functions indirectly, via a variable. For example:

obj = {

  on_init = function()
    print "hello."
  end,

  on_destroy = function()
    print "bye."
  end,

  on_do_something = function()
    print "doing something."
    error("Hi de hi, hi de ho!")
  end,

}

local event = "do_something"
local func = obj["on_" .. event]
func()

All works fine.

However, the problem is that when the called function raises an exception (as in the code above) the error message isn't quite clear. It is thus:

lua: test.lua:13: Hi de hi, hi de ho!
stack traceback:
    [C]: in function 'error'
    test.lua:13: in function 'func'
    test.lua:20: in main chunk

It says "in function 'func'". I'd prefer it to say "in function 'on_do_something'" instead.

I'd imagine this scenario to be very common. Is there a solution for this?

I tried calling the function thus:

obj["on_" .. event]()

But then the error message says "in function '?'", which isn't helpful either.

(I tried this code on Lua 5.1, 5.2 and LuaJIT without notable differences.)

Upvotes: 2

Views: 179

Answers (2)

Oliver
Oliver

Reputation: 29523

You have a few options. The debug module will try to produce something useful. For instance, you might be able to get the file name and line number where it was defined, if this is your own code. See http://www.lua.org/pil/23.1.html for the list of what is available via debug module. Or, you might be able to define the functions in the module, then add them to the table:

-- module something
function a() 
    ...
end

tt = {
    fn1 = a, 
    ...
}

Depending on where you trap the error (error handler installed via debug hook?), you could check if filename is the module where your table of functions is defined, and if it is, then use the debug module to print appropriate info based on your table structure etc; if it is not, just print the default traceback etc.

Upvotes: 0

lhf
lhf

Reputation: 72312

This is a limitation of the heuristics used by Lua to provide names for functions.

In Lua, all functions are anonymous. A given function can be the value of several variables: global, local, and table fields. The Lua debug system, which is used in error handling, tries to find a reasonable name for a value based on where it came from by looking into the bytecode being executed.

See Why is 'name' nil for debug.getinfo(1).

Upvotes: 2

Related Questions