Call a non-global function from a string variable

As expected, this code:

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

outputs:

bar

but either this:

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

or that:

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

outputs:

try to call the field '?' (nil value)
stack trace:
  test.lua: 4: in the main piece
  [C] :?

How to call a non-global function from a string variable?

+3
source share
1 answer
s = "bar"
foo = {
    bar = function() print(s) end
}
_G["foo." .. s]()

This last method does not work because there is no such table "foo.bar", but a field "bar"in the table foo. So you can call it like this:

_G.foo[s]()

or simply:

foo[s]()
+4
source

All Articles