Adding Touch Event Listeners dynamically

Hi all,

I’ve spent over two hours searching the forums and the net for a solution to my problem, but no luck as yet.

What I’m trying to do is ‘spawn’ new images at runtime, and add a touch event listener to them. I have copied my code below. When run, this code generates the following error at runtime (not compile time):

Runtime error
?:0: attempt to call method ‘getOrCreateTable’ (a nil value)
stack traceback:
[C]: in function ‘getOrCreateTable’
?: in function ‘addEventListener’

Can anyone see anything I’m obviously doing wrong and/or suggest how to add event listeners at runtime (ie, not with explicitly named variables). I’m new to learning LUA and Corona and so far its been good but this has me stumped.

[lua]-- Declare a new table to store ‘columns’ of blocks
local arrColumns = {}
arrColumns[1] = {}
arrColumns[2] = {}
arrColumns[3] = {}
arrColumns[4] = {}

– Touch event handler
function touchBlock( event )
print(“TOUCH TRIGGERED”)
end

– function to create a new ‘block’ image and attach a touch handler to it
function spawnNewBlock(columnIndex)
local columnLength = #arrColumns[columnIndex]
local newBlock = display.newImage(“block_square.png”)

newBlock.x = ((display.contentWidth / 4) * columnIndex) - horizontalCubeOffset
newBlock.y = display.contentHeight + (columnLength * 100)

– The following line generates a runtime error
newBlock.addEventListener( “touch”, touchBlock )

table.insert(arrColumns[columnIndex],newBlock)
end

– Run the spawn function to add a block to column 1
spawnNewBlock(1)[/lua] [import]uid: 9428 topic_id: 2320 reply_id: 302320[/import]

Close! Just change the line to newBlock:addEventListener( “touch”, touchBlock )

Note the colon in newBlock:addEventListener instead of the period

more details here http://developer.anscamobile.com/content/introduction#Dot_vs_Colon
[import]uid: 9064 topic_id: 2320 reply_id: 7081[/import]

Oh Wow, thanks so much, that was the problem…

Many thanks bherron, I thought I was going crazy [import]uid: 9428 topic_id: 2320 reply_id: 7102[/import]