Lua for loop reduce i? Strange behavior

Can someone explain this to me?

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

Output:

1
0
2
1
3
2
and so forth

I expected that I would change between 1 and 0. But, obviously, it continues to grow, as if I did not change it at all. What's happening?

I need to delete the i'th table element from time to time. So the next item to handle will be me again. In C, I would simply write -i at the end of my contents of the loop. Any official way in lua? :)

+4
source share
3 answers

(i ) , , , , ( for).

, while. . .

+6

while(true)? , .

local i = 5
while(true) do
    print(i)
    i = i - 1
    if (i == 0) then break; end
end
+2

.

" " , , - . undefined.

If you're really interested, check out your program list with luac. The loop control variable is assigned an internal name, so it cannot be changed. If the destination uses the same name, the local variable is synthesized as a backup. This prevents unintentional transformation forinto infinity.

You need another kind of loop.

+1
source

Source: https://habr.com/ru/post/1583820/


All Articles