Removing objects from a table

Is there any sample code that demonstrates the removal of objects from a table?

In this case, every frame I am checking for any objects that have fallen off the screen. If they have, I want to remove them from memory.

for i,val in ipairs(particles) do  
 if(val.y \> 320) then  
 particles[i]:removeSelf();  
 particles[i] = nil;  
 end  
end  

This works only on the first particle that falls off the screen, then the for loop no longer gets entered. This seems like a common task but I can’t find any examples of best practices. [import]uid: 52127 topic_id: 10714 reply_id: 310714[/import]

you can use this.

[lua]for i = 1, #toRemove do
toRemove[i].parent:remove(toRemove[i])
toRemove[i] = nil
end[/lua]

the example you posted should work if you use pairs instead

[lua]for i,val in pairs(particles) do
if(val.y > 320) then
val:removeSelf();
particles[i] = nil;
end
end[/lua]
[import]uid: 48521 topic_id: 10714 reply_id: 38906[/import]

Hello jn19,

You would use that:

[lua]for i = #particles, 1, -1 do
if particles[i].x < 321 then
continue – Do not remove and go to next iteration
end
local child = table.remove(particles, i) – Remove object from array and get it
if child ~= nil then
display.remove(child) – Destroy the object. Better than removeSelf()
child = nil
end
end[/lua]
Regards.
Francisco. [import]uid: 11749 topic_id: 10714 reply_id: 38927[/import]

Thanks, this works.

Can you explain why display.remove(child) is better than removeSelf()? [import]uid: 52127 topic_id: 10714 reply_id: 39001[/import]

@jn19,
even the removeSelf() will work, but the only thing that a lot of developers fail to notice is that in a list, if you are trying to remove items, always try to remove from the end/bottom

so the for loop has to be

for i=#elements,1,-1 do

not

for i=1,#elements do

cheers,

?:slight_smile: [import]uid: 3826 topic_id: 10714 reply_id: 39002[/import]

Hello,

jn19: display.remove(object) do same than object:removeSelf() but before verify object not = nil and removeSelf not verify and may crash.

Regards.
Francisco. [import]uid: 11749 topic_id: 10714 reply_id: 39137[/import]