I have a lua pseudo-class, with a method that creates a handful of buttons with touch listeners. From inside the touch listener declaration I want to access my class variables, but I can’t because “self” no longer works the way it does outside the listener.
I’ve looked at using object listeners as described at http://developer.coronalabs.com/reference/index/objectaddeventlistener but they don’t seem to fit my use case. How can I access the “_board” variable from within the listener? Thanks!
[lua]Game = {}
Game.__index = Game
– Constructor
function Game:new()
- Initialize a class variable “_board” and associate it with Game
local o = {_board = {}}
setmetatable(o, Game)
return o
end – new()
function Game:doSomething()
– Draw 5 button images down the left side of the screen every 100 pixels
for i = 0, 5, 100 do
local button = display.newImage(“foo.png”, 0, i)
– Make the buttons touch sensitive
function button:touch(event)
if event.phase == “ended” then
– This is where the problem is. “self” no longer refers to the class
– so the following prints ‘nil’. However if I print the variable outside
– the button:touch function, it prints the table address as expected
print(self._board)
end --if
end – function
button:addEventListener(“touch”)
end – for loop
end[/lua]
I apologize if this has already been asked but I couldn’t find it by searching. Thanks again! [import]uid: 42158 topic_id: 28990 reply_id: 328990[/import]