lua-users home
lua-l archive

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


Reyn asked how an anonymous function can find itself.

I suggested the following; apparently it worked. I don't know whether it 
is good Lua or not :) but in case anyone else is looking to solve this 
particular problem, I figured I might as well post it:

> Yes, thats what I do, but I thought there might be a way to address an 
> anonymous
> function inside itself, guess not.

Technically, there is: you can use debug.getinfo(1, "f").

However, it is not a very efficient way of doing things (since it
constructs a table) and anyway you should not expose the debug
interface to an untrusted script.

You could easily write a C function that duplicated the
functionality, though:

/* Untested, see page 35 of the manual */
int whoami(lua_State *L) {
  lua_Debug ar;
  return lua_getstack(L, 1, &ar) 
         && lua_getinfo(L, "f", &ar);
}