Search code examples
for-loopluadecrement

Lua for loop reduce i? Weird behavior


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? :)


Solution

  • 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.