Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua for loop reduce i? Weird behavior [duplicate]

Can someone explain me this?

for i = 1, 5 do
  print(i)
  i = i - 1
  print(i)
end

Output is:

1
0
2
1
3
2
and so forth

I exspected i to alter between 1 and 0. But obviously it keeps increasing as if I did not change it at all. What's going on?

I have to delete an i'th table element every now and then. So the next element to process would be i again. In C I would just write --i at the end of my loop content. Any official way in lua? :)

like image 401
Piglet Avatar asked Mar 13 '26 15:03

Piglet


1 Answers

The loop index (i in your case) is a variable local to the body of the loop, so any modifications you do to it have no effect on the loop conditions or the next element being processed (for the for loop).

If you need to have better control over the index to delete elements and keep processing, you should use the while loop form. See For Statement section for details.

like image 58
Paul Kulchenko Avatar answered Mar 16 '26 08:03

Paul Kulchenko