Quick question about removing from tables

If i am removing an enemy from a table do I need to nil him out after remove like so

[lua]for i=1, #onScreenFish do

if onScreenFish[i].canRemove == true then
onScreenFish[i]:removeSelf()
table.remove(onScreenFish, i)
onScreenFish[i] = nil
fishCounter=fishCounter-1
spawnNewFish()
break
end

end[/lua]

or just leave it out

[lua]for i=1, #onScreenFish do

if onScreenFish[i].canRemove == true then
onScreenFish[i]:removeSelf()
table.remove(onScreenFish, i)
–REMOVED HERE–
fishCounter=fishCounter-1
spawnNewFish()
break
end

end[/lua]

I’ve been using the top method and some times my enemies, which use translate to move, just stop. I’m assuming it’s because another has been removed and it is interfering.

Any help would be appreciated.

Cheers [import]uid: 26289 topic_id: 21288 reply_id: 321288[/import]

In your first example, when you do the table.remove(onScreenFish, i), that cell is removed, and what was onScreenFish[i+1] is now onScreenFish[i] so when you nil that, you’ve lost an object, leaked memory and you still end up with an empty cell in the table.

for i=1, #onScreenFish do  
  
 if onScreenFish[i].canRemove == true then  
 onScreenFish[i]:removeSelf()  
 onScreenFish[i] nil  
 table.remove(onScreenFish, i)  
 fishCounter=fishCounter-1  
 spawnNewFish()  
 break   
 end  
  
end  

That should be safe. Though just to be sure, I might be tempted to drop a collectgarbage(“collect”) before the table.remove just to make sure we are not leaking memory.
[import]uid: 19626 topic_id: 21288 reply_id: 84312[/import]

Hey Rob cheers for the reply.

That is actually how I used to have it. I just changed it today to see what would happen. Good to know it was the right way but frustrating because i’m still left with the enemies stopping scenario. It doesn’t happen every time so it’s hard to know whats going on.

I now switched to this. The backwards count way. Do you think this is better?

[lua]for i= #onScreenFish,1,-1 do – CHANGED

if onScreenFish[i].canRemove == true then
onScreenFish[i]:removeSelf()
onScreenFish[i] = nil
table.remove(onScreenFish, i)
fishCounter=fishCounter-1
spawnNewFish()
end

end[/lua]
Also was the break necessary in my original example. Can’t remember where that came from but it seems pointless? [import]uid: 26289 topic_id: 21288 reply_id: 84320[/import]