@TokOut, let me see if I can better explain what I’m trying to do.
The basic idea is that there will be buttons to tell the ship to turn, accelerate, and fire. There will be methods on Ship class, accelerate, turnLeft, turnRight, fire. So I want to create Buttons, each one bound to a specific one of those methods, and as it happens I want to create those above Ship, not inside Ship. That makes at least some difference in details.
So inside Button, when it figures out that it has been touched, it wants to have something, I called it “action”, that is bound to ship1:accelerate, or ship2: turnLeft and so on. I didn’t know how to do a function closure for some reason. So what I wanted to do originally was pass in the string for the function name on ship (“accelerate”, “turnLeft”, and so on), and inside Button, use that string to call the function.
It turns out that in Lua, writing ship.accelerate really means ship[“accelerate”], no more and no less. So you could say, if self.action contains “accelerate”, self.shipself.action and that would fetch the function named “accelerate” and call it. BUT … since Ship is an object, I really want to call self.ship:accelerate(), which passes the ship in as the self argument. But I couldn’t find a syntax that allowed that so wound up using self.shipself.action, and my question was if there was a simpler way.
Now @yojimbo2000 suggests passing a “function closure”. Basically a closure is a partly-applied function call, which can be completed later. In the case I did, I defined function f:
local f = function() ship1:accelerate() end
and then passed f to the Button:
button = Button(x, y, f)
Now in this case, f has not been called yet (since I didn’t say f() in the button creation, so inside the Button if I save that parameter in, say action:
Button:init(x,y,action)
self.action = action
...
end
then when the button wants to do the action, it just says:
self.action()
Adding the parens calls the function that is stored in self.action, namely my function f. f, in turn, calls ship1: accelerate
, which is what we want.
This is all rather arcane, and kind of advanced, so if you’re new to Lua and/or to programming with closures, it’s tricky to understand. I found it tricky myself, though I understand it when done this way. I think @yojimbo2000 has another way in mind and I’m not sure I understand that yet.
Does that help? I hope so.