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

1
2
3
4
5
6
7
8
9
10
11
12
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

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.

1
2
3
4
5
6
7
8
9
10
11
12
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

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?

1
2
3
4
5
6
7
8
9
10
11
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
views:1689 update:2012/2/7 8:40:54
corona forums © 2003-2011