【问题标题】:Call non-global function from string variable从字符串变量调用非全局函数
【发布时间】:2014-02-08 16:16:24
【问题描述】:

正如所料,这段代码:

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]: ?

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

【问题讨论】:

    标签: string lua lua-table


    【解决方案1】:
    s = "bar"
    foo = {
        bar = function() print(s) end
    }
    _G["foo." .. s]()
    

    最后一种方法不起作用,因为没有这样的表"foo.bar",而是表foo 中的字段"bar"。所以你可以这样称呼它:

    _G.foo[s]()
    

    或者简单地说:

    foo[s]()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      相关资源
      最近更新 更多