Touch Listeners In For Loop - Assertion Failed

Not sure what I'm doing wrong here.

Basically, I've created a grid layout of rectangles using a for loop.

1
2
3
4
5
6
for i = 1, 10 do
 
        local myRect = display.newRect(0, 0, 20, 20)
...
 
end

Do it like this :

1
2
3
4
5
6
7
8
9
local function myFunction(event)
end
 
local rects = {}
 
for i = 1, 10 do
        rects[i] = display.newRect(0, 0, 20, 20)
        rects[i]:addEventListener("tap", myFunction)
end

Thanks for the quick reply Danny. I'll give that a go right now.

@Danny That works great thanks. One other thing though...

Using your above example, let's say that I wanted to use the listener to pass a parameter to myFunction. Can this be done?

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
local function myFunction(event)
 
        -- Print 'rectangleNumber' from passed parameter (below)
 
end
 
local rects = {}
 
for i = 1, 10 do
        rects[i] = display.newRect(0, 0, 20, 20)
 
        -- Create a string variable to use as a parameter later 
      
        local rectangleNumber = "rectangle"..i
 
        -- How can rectangleNumber (above) be passed to myFunction?
 
        rects[i]:addEventListener("tap", myFunction)
end

Sure :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
local function myFunction(event)
        local target = event.target
 
        print(target.name)
end
 
local rects = {}
 
for i = 1, 10 do
        rects[i] = display.newRect(0, 0, 20, 20)
 
        -- Create a string variable to use as a parameter later 
      
        rects[i].name = "rectangle" .. i
 
        -- How can rectangleNumber (above) be passed to myFunction?
 
        rects[i]:addEventListener("tap", myFunction)
end

Once you've created your array of display objects, you can assign any number of properties to each object, e.g.

1
2
rect[i].id = i
rect[i].canTouch = true

Awesome - works perfectly thank you.

Great support and community once again.

Glad to help :)

views:1741 update:2012/2/7 8:40:54
corona forums © 2003-2011