Creating Touch Events on the fly

Please help me,

Basically what I want to know how to do is be able to create many buttons based on a code and then be able to detect which one is pressed.

For example, say there is a program which places a button wherever the user presses on the screen. The button is referenced as button[1],button[2],button[3] etc. As the user adds another button, the number goes up by one. This, I can do. The part that I am having difficulty with is figuring out which button is pressed, since the normal method of:
[lua]function button[1]:tap(event)

end[/lua]
is unusable due to the high amounts of buttons, and not knowing how many buttons there are going to be.

Is there any way I can make them all listen for touches, then tell me what the value of x is in the button[x] that was pressed?

Hopefully you can understand what i’m asking for.
Thanks in advance! [import]uid: 38148 topic_id: 20592 reply_id: 320592[/import]

Here’s an example that has the buttons added in a for loop;

[lua]display.setStatusBar (display.HiddenStatusBar)

local function getCoords (event)
print (event.target.x, event.target.y)
end

local button = {}

for i = 1, 10 do
ranX, ranY = math.random(10,295), math.random(10,440)
button[i]=display.newRect( ranX, ranY, 30, 15 )
button[i]:addEventListener(“tap”, getCoords)
end[/lua]

Obviously yours are not but as you can see there’s a preexisting function, getCoords, which each new button listens for and when tapped prints the coordinates.

Does this help?

Peach :slight_smile: [import]uid: 52491 topic_id: 20592 reply_id: 80786[/import]

Perfect!

Thanks! :smiley: [import]uid: 38148 topic_id: 20592 reply_id: 80799[/import]

Excellent!

Peach :slight_smile: [import]uid: 52491 topic_id: 20592 reply_id: 80809[/import]