Question

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 this:

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

outputs:

attempt to call field '?' (a nil value)
stack traceback:
test.lua:4: in main chunk
[C]: ?

How to call non-global function from string variable?

Was it helpful?

Solution

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

This last method doesn't work because there is no such table "foo.bar", but rather the field "bar" in the table foo. So you can call it like this:

_G.foo[s]()

or simply:

foo[s]()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top