在löve2D中使用lua的for循环,删除变量

我对编程有一点初学者的经验,我的英语不是很好,我希望我能用清晰的语言表达出我的问题:

所以我的代码中有一个for循环,并且在其中有两个if。在每个if中,我都会检查一些条件是否为真或假,如果为真,我就会删除该循环的某个部分。就像这样:

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

这就是我的代码,我的问题是,如果第一个if导致了Test[n]的删除,那么游戏就会在下一个if中崩溃,因为Test[n]不再存在。我通过制作两个for循环来解决这个问题,一个用于每个if

但我看到有人不用两个for循环就做到了,而且没有崩溃,我试着找出问题在哪里,但我找不到。

如果有人能找到我写的哪里有问题,我将不胜感激!

所以这是我的代码中遇到问题的时间,第9行,如果条件满足,我table.remove(ListeTirs,n),然后在第17行,当代码尝试再次找到它进行测试时,它出错:

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

我希望这很清楚,我可以发布整个代码,但我觉得没必要,如果需要,我会添加它。

谢谢:)

点赞
用户1847592
用户1847592
# 删除被标记的元素

对于n=#Test,1-1 do
   local should_be_removed

   --只标记删除
   如果Test [n] .delete = true then
   应该被删除 = true
   结束

   - 只标记删除
   如果Test [n] .y> 0 then
   应该被删除 = true
   结束

   --实际删除(在循环体的最后)
   如果应该被删除,则
   table.remove(Test,n)
结束
2016-12-17 18:56:49