lua-users home
lua-l archive

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

You have seen them all too often.

stdin:1: bad argument #1 to 'sqrt' (number expected, got string)
stdin:1: bad argument #1 to 'getlocal' (level out of range)

They can be issued from the C API by these:

    void luaL_checktype (lua_State *L, int arg, int t);
    void luaL_argcheck (lua_State *L, int cond, int arg, const char *extramsg);
    int luaL_argerror (lua_State *L, int arg, const char *extramsg);

You can fake them from inside Lua, easy enough. For example, I have:

    argcheck = function(cond,pos,fct,msg)
       if not cond then
          error(("bad argument "..pos.." to '%s' (%s)"):format(fct,msg))

Notice the difference? The C API knows the name of the calling
function, the Lua function has to be told what it is.

How hard is it for a running function to find out the name of the
function from which it was called?

Look at this.

     function fct(x,y) return x+y end
     adder = fct
     fct = nil
     print (adder("1","a"))

You get a standard error message that says:

stdin:1: attempt to perform arithmetic on local 'y' (a string value)
stack traceback:
	stdin:1: in function 'adder'
	stdin:1: in main chunk
	[C]: in ?

I want that name "adder" in my own customized message (not
always an error message) that can be issued from inside the
body of "fct". I don't wnat the name `fct` that appears in
`function fct(x,y)`, the one I can easily pass to my `argcheck`.
It's useless.

I've snooped around with debug.getlocal and debug.getinfo and
I can't find it.