how to add touch listener to objects created with a for loop

Hello all, I have been struggling with creating an item inventory for my game.

Right now, I have a table that holds all my items and I use a for loop to draw the inventory images to the screen.

 for i=1, #equipInventory do if i \< 5 then local setX = 460 local setY = 220 InventoryDisplay\_i = display.newSprite( itemSheet, itemSequenceData ) InventoryDisplay\_i:setFrame(equipInventory[i].frame) sceneGroup:insert(InventoryDisplay\_i) InventoryDisplay\_i.x = setX + (i \* 120) InventoryDisplay\_i.y = setY end

my struggle now is trying to make the drawn images inter-actable. I have tried to add into the for loop the touch listener

InventoryDisplay\_i:addEventListener( "touch", equipItems )

But that does not work, I seem to be having trouble identifying the name of the images that are to be drawn, I assumed that they would be InventoryDisplay_1, InventoryDisplay_2, InventoryDisplay_3, and so on, but that does not seem to be the case.

any help would be great

When you use InventoryDisplay_i, the “i” is not the numerical “i” from the for loop.  It is literally just “InventoryDisplay_i” every iteration.  

Instead you should add each object to a table like:

local InventoryDisplay = {} ... for i=1, #equipInventory do if i \< 5 then local setX = 460 local setY = 220 InventoryDisplay[i] = display.newSprite( itemSheet, itemSequenceData ) InventoryDisplay[i]:setFrame(equipInventory[i].frame) sceneGroup:insert(InventoryDisplay[i]) InventoryDisplay[i].x = setX + (i \* 120) InventoryDisplay[i].y = setY InventoryDisplay[i]:addEventListener( "touch", equipItems ) end

Thanks man, I just worked this into my code and everything works.

When you use InventoryDisplay_i, the “i” is not the numerical “i” from the for loop.  It is literally just “InventoryDisplay_i” every iteration.  

Instead you should add each object to a table like:

local InventoryDisplay = {} ... for i=1, #equipInventory do if i \< 5 then local setX = 460 local setY = 220 InventoryDisplay[i] = display.newSprite( itemSheet, itemSequenceData ) InventoryDisplay[i]:setFrame(equipInventory[i].frame) sceneGroup:insert(InventoryDisplay[i]) InventoryDisplay[i].x = setX + (i \* 120) InventoryDisplay[i].y = setY InventoryDisplay[i]:addEventListener( "touch", equipItems ) end

Thanks man, I just worked this into my code and everything works.