Reputation: 2974
Suppose the Lua stack is set up for an upcoming function call (with lua_pcall()
).
To make things concrete, let's suppose the function takes one string argument, and that the stack does not contain any other Lua objects below the function. That is, the stack would look like this:
Lua stack at 1 = a LUA_TFUNCTION
Lua stack at 2 = a LUA_TSTRING
How can one get the name of the function from such a stack?
I tried lua_tostring()
, and luaL_getmetafield()
(with e
= "__name"
), but those functions do not work for this purpose.
Upvotes: 2
Views: 3483
Reputation: 473192
Speaking in the most general sense, functions do not have names. They are values, like any other. The name you use to access a function in one instance need not match the name you use in another, since you can just copy the functions around.
However, the Lua compiler does recognize that if you create a function with a statement of the form function <name>(...) end
, that <name>
is important to the function that is being created. This name is used purely for debugging purposes (you can fetch this "name" of a function via lua_getinfo
in the C API), so there is no guarantee that you can use this name in any real sense to find/access this function.
Upvotes: 6
Reputation: 5847
Lua values (function is just a value, like a number) has no names.
The function value that you find on stack is a result of expression evaluation, which could involve reading some variable (and probably you think that is a name of a function), or constructing new function in-place. On stack you get a result of expression, without possibly knowing which variable was read, if any at all.
If you really do need to have some unique name associated with the function, you must track those names/ids in your own table, accessible from the native side. Then you could easily lookup the name by the function value.
If it's not your code, but you still need to distinguish between functions, you can try to build that lookup table yourself, iterating the environment you want to monitor. That still can fail if environment is dynamically updated. Same variable can store any other function later.
But in general case - forget about the names, as values has no names.
Upvotes: 4