For-loop in lua with löve2D, deleting variable

97 views Asked by At

i'm a bit beginner about coding, and my english isn't great, i hope i'll be able to make my question clear:

So I have a for-loop in my code, and 2 if in it, in each if, I see if something is true or false, if it's true, I delete a portion of the loop. like that:

for n=#Test,1, -1 do

   if Test[n].delete == true then 
      table.remove(Test, n )
   end

  if Test[n].y > 0 then
      table.remove(Test, n )
  end

end

kind of like that, and my problem is, if the first if make Test[n] being deleted, then the game crash at the next if because Test[n] Doesn't exist anymore. I solved the problem by making 2 for-loop, one for each if.

But I saw someone who did it without 2 for-loop, and it's not crashing, I tried to figure what was wrong but I can't find it.

If someone could find what is wrong with what I wrote, I would be thankful!

So here is the moment that makes problem in my code, on line 9, if the condition are met, i table.remove(ListeTirs, n ), then on line 17, when code try to find it again for test it, it bug :

for n=#ListeTirs,1, -1 do
  if ListeTirs[n].Type == "Gentils" 
  then local nAliens
    for nAliens=#ListeAliens,1,-1 do
      if
      Collide(ListeTirs[n], ListeAliens[nAliens]) == true
      then
      ListeTirs[n].Supprime = true
      table.remove(ListeTirs, n ) 
      ListeAliens[nAliens].Supprime = true
      table.remove(ListeAliens, nAliens)
      end
    end
  end  

  if
    ListeTirs[n].y < 0 - ListeTirs[n].HauteurMoitie or ListeTirs[n].y > Hauteur + ListeTirs[n].HauteurMoitie or ListeTirs[n].x > Largeur + ListeTirs[n].LargeurMoitie or ListeTirs[n].x < 0 - ListeTirs[n].LargeurMoitie
    then

    ListeTirs[n].Supprime = true
    table.remove(ListeTirs, n)


  end 

end

I hope it's clear, I could post the whole code but I don't feel it's necessary, if it is, I will add it.

Thank you :)

1

There are 1 answers

1
Egor Skriptunoff On
for n=#Test,1, -1 do
   local should_be_removed

   -- just mark for deletion
   if Test[n].delete = true then 
      should_be_removed = true
   end

   -- just mark for deletion
   if Test[n].y > 0 then
      should_be_removed = true
   end

   -- actually delete (at the very end of the loop body)
   if should_be_removed then
      table.remove(Test, n )
   end
end