Multiple squares - which one was clicked (addEventListener to table)

Hi All,

I’m new to Corona, and I’m playing around with some ideas…

Here I have (in landscape mode) a grid of squares. I need to add some kind of event listener, so I know which square the user touched.

Please help :slight_smile:

Cheers,
Michael

Code:
display.setStatusBar( display.HiddenStatusBar )
local function buttonHandler(event)
myAlert = native.showAlert(
“Alert!”,
“This is either a desktop or device native alert dialog.”,
{ “Cancel”, “OK” }
);
end

local squares = {}

for i = 1, 8 do
for j = 1, 5 do
local index = j + ((i-1) * 2) – a counter from 1 to …
squares[index] = display.newRect(-30+(i*53), 20+(5*53) - (j*53),50,50)
squares[index]:setFillColor(255,255,100)
squares[index].id = “square”
squares[index].touch = onTap
squares[index]:addEventListener( “touch”, squares[index] )

end
end
local function onTap(self, event)
labelsTap= display.newText(“hello”, 5, 33,native.systemFont, 24)
– Would be great to know here which square was touched

end [import]uid: 12916 topic_id: 4728 reply_id: 304728[/import]

The short answer is to use event.target
That is, in onTap() when you refer to event.target that’s the square that was touched.

More robust however is to work in an object-oriented way. Then you can use the parameter “self” in onTap() to refer to the current square.

This methodology is alluded to here
http://developer.anscamobile.com/content/introduction#Object_Methods

It’s explained a little further here
http://www.lua.org/pil/16.html

Neither is super clear however. I’m so familiar with OOP before starting to work with Corona that it didn’t even occur to me the explanations are kind of poor.

This is off the top of my head so not exact, but the code would be something like

function DisplayObject:onTap(self, event) print(self.id) end function [import]uid: 12108 topic_id: 4728 reply_id: 15038[/import]