Batch remove physics objects

I have some physics objects which I want to remove when my game over function is called. I loop through my data table (refuse) and try to remove them if they exist on the screen. I tried removing the group that they are all in but if an object is touched before and released after the game over my app crashes, presumably because the touch event is unresolved. Here is some code, please help me:

-------------------  
function fadeOutDestroy( body )  
 local body = body  
 local destroy = function()  
 body:removeEventListener( "touch" , dragRefuse )  
 body:removeSelf()  
 body = nil  
 end  
 transition.to( body, { time=500, delay=500, alpha=0, onComplete=destroy } )   
end  
-------------------  
--\> loop through the refuse data table and remove objects from screen   
for i=1, #refuse do  
 if refuse[i].object then  
 local body = refuse[i].object  
 print ( body.name )  
 fadeOutDestroy( body )  
 end  
end  
-------------------  

…But the corona terminal returns a runtime error saying: ‘attempt to call method ‘removeSelf’ (a nil value)’ [import]uid: 11712 topic_id: 10929 reply_id: 310929[/import]

It looks like when you are calling the “fadeOutDestroy” function the body is being removed within the “destroy” function and then the transition.to is attempting to call “destroy” again at which point the body had already been removed so it contains nil. Try removing the “onComplete=destroy” call from the transition. [import]uid: 27965 topic_id: 10929 reply_id: 39779[/import]

But the local ‘destroy’ function only gets called within my ‘fadeOutDestroy’ function when the alpha transition has been completed. If I remove the onComplete call surely that would just fadeout all the objects but not actually remove anything from the physics engine or their touch event listeners ? [import]uid: 11712 topic_id: 10929 reply_id: 39783[/import]

My apologies. You are correct. I guess I shouldn’t try to answer questions until after the caffeine kicks in. The only thing that I can see is that there might be a conflict with using the name “body” for two different tables. Maybe try renaming the local inside “fadeOutDestroy” to something like “tempBody” instead of “body”. [import]uid: 27965 topic_id: 10929 reply_id: 39842[/import]

not sure if this will help but try looping backwards…
[lua]for i=#refuse, 1, -1 do
if refuse[i].object then
local body = refuse[i].object
print ( body.name )
fadeOutDestroy( body )
end
end[/lua] [import]uid: 48521 topic_id: 10929 reply_id: 39887[/import]