Decreasing the number of times a loop runs

I am running a loop which checks the x value of each object in the table.
One of the objects gets removed from the table durring the looping process.
This causes an error because the loop then tries to check for more items then are actually in the table.

 

What I need to do is break the loop and then run it again one less time,
or preferably some how decrease the number of times the loop runs.  Not sure how though.  Thanks


function removeFromTable()

for i = 1,#objectTable do

if objectTable[i].x <= 0 then

table.remove(objectTable,i)

end

end

end


A common approach to addressing situations like this is to loop through your table backwards.  That way, if you remove an element, the ones above it shift down, but you can continue moving backwards through the loop without a problem.  Try this:

[lua]

function removeFromTable()

   for i = #objectTable,1,-1 do    – Loop through the table backwards

      if objectTable[i].x <= 0 then

         table.remove(objectTable,i)

      end

   end

end

[/lua]

  • Andrew 

Awesome, so simple but exactly what I was looking for.

A common approach to addressing situations like this is to loop through your table backwards.  That way, if you remove an element, the ones above it shift down, but you can continue moving backwards through the loop without a problem.  Try this:

[lua]

function removeFromTable()

   for i = #objectTable,1,-1 do    – Loop through the table backwards

      if objectTable[i].x <= 0 then

         table.remove(objectTable,i)

      end

   end

end

[/lua]

  • Andrew 

Awesome, so simple but exactly what I was looking for.