Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 从字符串变量调用非全局函数_String_Lua_Lua Table - Fatal编程技术网

String 从字符串变量调用非全局函数

String 从字符串变量调用非全局函数,string,lua,lua-table,String,Lua,Lua Table,正如预期的那样,此代码: s = "bar" bar = function() print(s) end _G[s]() 产出: 酒吧 但要么是: s = "bar" foo = { bar = function() print(s) end, _G["foo." .. s]() } 或者这个: s = "bar" foo = { bar = function() print(s) end } _G["foo." .. s]() 产出: 尝试调用字段“?”(一个空值

正如预期的那样,此代码:

s = "bar"
bar = function() print(s) end
_G[s]()
产出:

酒吧

但要么是:

s = "bar"
foo = {
    bar = function() print(s) end,
    _G["foo." .. s]()
}
或者这个:

s = "bar"
foo = {
    bar = function() print(s) end
}
_G["foo." .. s]()
产出:

尝试调用字段“?”(一个空值)
堆栈回溯:
test.lua:4:在主块中
[C] :

如何从字符串变量调用非全局函数

s = "bar"
foo = {
    bar = function() print(s) end
}
_G["foo." .. s]()
最后一种方法不起作用,因为没有这样的表
“foo.bar”
,而是表
foo
中的字段
“bar”
。所以你可以这样称呼它:

_G.foo[s]()
或者简单地说:

foo[s]()