对不起,如果这太明显了,但我是lua的新手,我在参考资料中找不到它. 在Lua中是否有一个NAME_OF_FUNCTION函数,给定一个函数给我它的名字,以便我可以用它索引一个表?我想要的原因是我想做
在Lua中是否有一个NAME_OF_FUNCTION函数,给定一个函数给我它的名字,以便我可以用它索引一个表?我想要的原因是我想做这样的事情:
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
根本没有这样的功能.我想没有这样的功能,因为功能是一等公民.所以函数只是一个像变量一样引用的值.因此,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))
由于metatable查找,这将比使用裸函数慢一点.并且它不会阻止任何人更改状态中函数的名称,更改包含它的表中的函数名称,更改函数等等,因此它不是防篡改.您也可以通过像fun1.fun这样的索引来剥离表格,如果将它作为模块导出它可能会很好,但是你可以放弃你可以放入metatable的命名和其他技巧.
