touch addEventListener with dynamic items, help needed.

I am having trouble getting the touch event work on objects that I’ve created dynamically. I must be doing something wrong…

Can someone please shed some light?

thanks in advance!

[lua]------------------------------------------------------

local levelMen = {1,1,2}
local guys = {}

local function touchGuy( self, event )
print(“touched guy”) --> prints that the guy was touched"
print(" guy = " … self.myName) --> here is the error
–>main.lua:132: attempt to concatenate field ‘myName’ (a nil value)
end

local function loadallmen()

local array = levelMen
print( table.concat( array, " " ) )

for i=1,#array do
print(array[i]) --> prints the men types “1,2,3” etc
guys[i] = display.newImage( “man-”… array[i] …".png", 40 + (i*50), 220 )
guys[i].inMode = “startup”
guys[i].myName = “zombie” … array[i]
print(guys[i].myName) --> prints the name “zombie1” etc.
guys[i]:addEventListener(“touch”,touchGuy)
physics.addBody( guys[i], { density=1.0, friction=0.95, bounce=0.5 } )
gameGroup:insert(guys[i] )

end

end
-----------------------------------------------------------[/lua] [import]uid: 21962 topic_id: 6320 reply_id: 306320[/import]

The “self” keyword only really applies to object methods denoted with a colon, not to regular functions. The way you have that written the word “self” does in fact have a meaning, but not the meaning you intend and thus it’s just confusing; get rid of it. Meanwhile, the event object has a parameter “target” that refers to the object touched. Rewrite your code thusly:

local function touchGuy(event) print("touched guy") print(" guy = " .. event.target.myName) end [import]uid: 12108 topic_id: 6320 reply_id: 21837[/import]

thanks jhocking! explains a lot, and makes sense now! [import]uid: 21962 topic_id: 6320 reply_id: 21851[/import]