For-loop in lua with löve2D, deleting variable
<p>i'm a bit beginner about coding, and my english isn't great, i hope i'll be able to make my question clear:</p>

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

<pre><code>for n=#Test,1, -1 do

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

  if Test[n].y &gt; 0 then
      table.remove(Test, n )
  end

end
</code></pre>

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

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

<p>If someone could find what is wrong with what I wrote, I would be thankful! </p>

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

<pre><code>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 &lt; 0 - ListeTirs[n].HauteurMoitie or ListeTirs[n].y &gt; Hauteur + ListeTirs[n].HauteurMoitie or ListeTirs[n].x &gt; Largeur + ListeTirs[n].LargeurMoitie or ListeTirs[n].x &lt; 0 - ListeTirs[n].LargeurMoitie
    then

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


  end 

end
</code></pre>

<p>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.</p>

<p>Thank you :)</p>