正如预期的那样,这段代码:
s = "bar"
bar = function() print(s) end
_G[s]()
输出:
bar
但是要么这样:
s = "bar"
foo = {
bar = function() print(s) end,
_G["foo." .. s]()
}
或者这个:
s = "bar"
foo = {
bar = function() print(s) end
}
_G["foo." .. s]()
输出:
attempt to call field '?' (a nil value)
stack traceback:
test.lua:4: in main chunk
[C]: ?
如何从字符串变量调用非全局函数?
最佳答案
s = "bar"
foo = {
bar = function() print(s) end
}
_G["foo." .. s]()
最后一个方法不起作用,因为没有这样的表 "foo.bar"
,而是表 foo 中的字段
。所以你可以这样调用它:"bar"
_G.foo[s]()
或者简单地说:
foo[s]()
关于string - 从字符串变量调用非全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21643550/