Reputation: 4986
How can you call a function name via a string in Lua on self
?
I tried the techniques described on the similar question (lua call function from a string with function name), however this only addresses calling functions that exist on the global table, or through modules; it does not work on self
.
Here is a simplified example of what I'm trying to do.
function CardsScene:onEnterFrame()
if self.transition_complete then
loadstring("self.basicMathInit")()
end
end
function CardsScene:basicMathInit()
print("Init has been called.")
end
This results in the following error.
scenes/CardsScene.lua:83: attempt to call a nil value
Upvotes: 3
Views: 3782
Reputation: 473232
self
is not magic. It's just a local variable, no different from any other Lua variable.
If you want to get a global function by its string name, you would access the global table with that string: _G[string_name]
. _G
is not magic; it's just a table.
Just like self
. So you would do the exact same thing for getting access to members of self
by name: self[string_name]
. If that represents a function, you would call it with function call syntax: self[string_name]()
.
Upvotes: 5