3

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
Community
  • 1
  • 1
bigtunacan
  • 4,873
  • 8
  • 40
  • 73
  • Pedantic: Functions are values; No value has a name. The left part of a function call—before the parentheses—is an expression. If the expression does not evaluate to a function value, the call is in error. Method call syntax is slightly different: The expression to the left of the colon should evaluate to a value, which, when indexed by the field name to the right of the colon, should evaluate to a function value. The first value is passed as the first parameter (`self` if the function definition uses the method syntax) and is typically a table. – Tom Blodget May 03 '16 at 04:43

1 Answers1

5

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]().

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • Thanks, everything I had seen covers using loadstring to do this which was always failing. – bigtunacan May 03 '16 at 03:38
  • with that syntax self does not seem to be populated in the method which is called. Any solution for that? – J R Apr 10 '23 at 18:53
  • @JR: The question did not use `self:` syntax for calling the function, so it would be inappropriate for this answer to give `self` as a parameter to the function. – Nicol Bolas Apr 10 '23 at 18:57