Sorry if this is too obvious, but I am a total newcomer to lua, and I can’t find it in the reference.
Is there a NAME_OF_FUNCTION function in Lua, that given a function gives me its name so that I can index a table with it? Reason I want this is that I want to do something like this:
local M = {}
local function export(...)
for x in ...
M[NAME_OF_FUNCTION(x)] = x
end
end
local function fun1(...)
...
end
local function fun2(...)
...
end
.
.
.
export(fun1, fun2, ...)
return M
There simply is no such function. I guess there is no such function, as functions are first class citizens. So a function is just a value like any other, referenced to by variable. Hence the
NAME_OF_FUNCTIONfunction wouldn’t be very useful, as the same function can have many variable pointing to it, or none.You could emulate one for global functions, or functions in a table by looping through the table (arbitrary or _G), checking if the value equals x. If so you have found the function name.
Another approach would be to wrap functions in a table, and have a metatable set up that calls the function, like this:
This will be a bit slower than using bare functions because of the metatable lookup. And it will not prevent anyone from changing the name of the function in the state, changing the name of the function in the table containing it, changing the function, etc etc, so it’s not tamper proof. You could also strip the tables of just by indexing like
fun1.funwhich might be good if you export it as a module, but you loose the naming and other tricks you could put into the metatable.