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]
[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]
@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