In Lua, is there a function that defines a function, does it return its name as a string?

Sorry if this is too obvious, but I am a complete newbie to lua and I cannot find it in the link.

Is there a NAME_OF_FUNCTION function in Lua that gives me a name so that I can index a table with it? The reason I want this is because 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
+5
source share
4 answers

. , , . , - , , . , NAME_OF_FUNCTION , , , .

, ( _G), , x. , .

a=function() print"fun a" end
b=function() print"fun b" end
t={
   a=a,
   c=b
}
function NameOfFunctionIn(fun,t) --returns the name of a function pointed to by fun in table t
   for k,v in pairs(t) do
       if v==fun then return k end
   end
end
print(NameOfFunctionIn(a,t)) -- prints a, in t
print(NameOfFunctionIn(b,t)) -- prints c
print(NameOfFunctionIn(b,_G)) -- prints b, because b in the global table is b. Kind of a NOOP here really.

, , , :

fun1={
    fun=function(self,...)
        print("Hello from "..self.name)
        print("Arguments received:")
        for k,v in pairs{...} do print(k,v) end
    end,
    name="fun1"
}
fun_mt={
    __call=function(t,...)
        t.fun(t,...)
    end,
    __tostring=function(t)
        return t.name
    end
}
setmetatable(fun1,fun_mt)
fun1('foo')
print(fun1) -- or print(tostring(fun1))

, - . - , , , .. .., . , fun1.fun, , , , .

+5

, export():

function export(...)
        local env = getfenv(2);
        local funcs = {...};
        for i=1, select("#", ...) do
                local func = funcs[i];
                for local_index = 1, math.huge do
                        local local_name, local_value = debug.getlocal(2, local_index);
                        if not local_name then
                                break;
                        end
                        if local_value == func then
                                env[local_name] = local_value;
                                break;
                        end
                end
        end
        return env;
end

API, Lua 5.2, , , , .

+1
0

(, , , Lua, ), (, locals globals Python), , , .

, .

, , , , . , ( eval - ), .

0

All Articles