adding listner to several objects at once

Hi :slight_smile:
I have a sound event that i want to associate with some of the objects of my scene. For example:
[lua]local function bing( self, event )
if ( event.phase == “began” ) then
audio.play( kick )
end
end
wood_1.collision = bing
wood_1:addEventListener( “collision”, wood_1 )
.
.
.
wood_39.collision = bing
wood_39:addEventListener( “collision”, wood_39 )[/lua]
so now i have 40 objects, and i must add separately a listener to all of them. It is possible to add a single listener that is valable for all the objects that name begins with wood?

many thanx for your help :slight_smile: [import]uid: 44010 topic_id: 8268 reply_id: 308268[/import]

When you have 40 identical items like that don’t put them in individual variables, put them in a table. Then it’s easy to loop through the table to do the same thing to all of them:

local wood = {} wood[1] = blah wood[2] = blah ... for i = 1, #wood do wood[i].collision = bing wood[i]:addEventListener("collision", wood[i]) end [import]uid: 12108 topic_id: 8268 reply_id: 29482[/import]

so the “blah” is the name of my wood piece?
like
wood[1] = wood_1
wood[2] = wood_2
ect…
?

wouldn’t it be more eficient to have a function that retrieve the first 4 letters of an object name and do function.bing on them?
[import]uid: 44010 topic_id: 8268 reply_id: 29484[/import]

No “blah” is whatever you do to create the pieces in the first place. You don’t need the individual variables, only the table:

wood[1] = newImage("wood.png") wood[1]:addBody(something or other) [import]uid: 12108 topic_id: 8268 reply_id: 29485[/import]

ok, i think i can handle it from now, many thx!!! :slight_smile: [import]uid: 44010 topic_id: 8268 reply_id: 29488[/import]