remove objects... it's not so easy

Hi all, if i put display object in an array like this:

 allClouds[#allClouds+1]=display.newImageRect("cloud.png",270,140)  
 group:insert(allClouds[#allClouds])  
 local cloud=allClouds[#allClouds]  

and than i remove the offscreen clouds like this:

local function removeOffscreenItems()  
 for i = 1, #allClouds do  
 local cloud = allClouds[i]  
 if (cloud.x) then  
 if cloud.x == 1200 or cloud.x ==-150 then  
 cloud:removeSelf()  
 print ("nuvola Rimossa!")  
 print (#allClouds)  
 end   
 end  
 end  
end  
  

What’s the situation of my array? I mean, this is really the way we destroy objects? why #allClouds don’t turn to 0? Will i have problem wile creating new clouds?

Thanks… [import]uid: 70929 topic_id: 23639 reply_id: 323639[/import]

You will find that if you go through an array in the forward direction, like you’re doing, and remove elements from the array, you will end up skipping elements.

Instead, go through your array backward:

[lua]for i=#allClouds,1,-1 do
–stuff
end[/lua] [import]uid: 44647 topic_id: 23639 reply_id: 94876[/import]

Thanks!!!
I go for a try :stuck_out_tongue: [import]uid: 70929 topic_id: 23639 reply_id: 94878[/import]

i got an error…
Runtime error
…p/lua projects/takethattomato-0.4 copia/director.lua:934: ERROR: table expected. If this is a function call, you might have used ‘.’ instead of ‘:’
stack traceback:
[C]: ?
[C]: in function ‘insert’
…p/lua projects/takethattomato-0.4 copia/director.lua:934: in function ‘_listener’
?: in function <?:441>
?: in function <?:214> [import]uid: 70929 topic_id: 23639 reply_id: 94885[/import]