Hello. Hope I am posting this in the right place, sorry if it is not.
I have a “Piece” class for a board game I am making that looks like this:
require "globals" local Piece = {} local Piece\_mt = { \_\_index = Piece} function Piece.New(type, img, gridPosX, gridPosY) local newPiece = {} newPiece.gridPosX = gridPosX; newPiece.gridPosY = gridPosY; newPiece.img = display.newImage(img, myGrid[gridPosX][gridPosY].x, myGrid[gridPosX][gridPosY].y); newPiece.thisPieceSelected = false; newPiece.availableMoves = {}; newPiece.type = type; myGrid[gridPosX][gridPosY].taken = type; return setmetatable( newPiece, Piece\_mt ) end
And (in the same file) I have class functions which interact with the data like for instance:
function Piece:getType() return self.type; end
The main problem is with adding an event listener to the “img”. I currently have a function called touch and another function called listen to add the listener like so:
function Piece:touch ( event ) --do stuff like calculating moves end function Piece:listen() self.img:addEventListener("touch", Piece); end
The problem is that while this works to some extent (program enters the Piece:touch function when I click the image) I can not access any of the data in the class inside Piece:touch. If i try to access for instance “self.type” it says it is a nil value. This works fine in other functions, like Piece:getType, but not in Piece:touch.
It used to work fine when I had both the Piece:touch function and the functions it used, as local functions inside the constructor, but I am now adding an AI that needs access to these functions, so they have to be outside the constructor (unless there is some way to call local functions inside the constructor from outside it, I could not find any way to do this). Does anyone know how I can access the data inside the class, while still having the listener function outside the constructor?
Another minor issue is that I can not figure out how to add the listener without using a separate function. As you can see the listener is now added through the Piece:listen function, is there any way to do this without a function call? I tried placing it right before “return Piece” in the class but got an error that self is nil.
Thanks in advance for any help