Unable to change loop variable in lua

im trying this in lua:

for i = 1, 10,1 do
    print(i)
    i = i+2
end

I expect the following output:

1,4,7,10

However, it idoesn't seem to be affected, so it gives me:

1,2,3,4,5,6,7,8,9,10

Can someone tell me a little about the background concept and what is the correct way to change the counter variable?

+4
source share
3 answers

As Colonel Thirty-two said, there is no way to change the loop variable in Lua. Or rather, more accurately, the Lua loop counter is hidden from you. The variable iin your case is just a copy of the current counter value . Therefore, its change does nothing; it will be overwritten by the actual hidden counter every time a loop cycle.

for Lua, , . , , ( ) - .

for - ; , while. , , ; .

+8

Numeric for , 1.

, :

for i = 1,10,3 do
    print(i)
end

, . , while ( , , ):

local i = 1
while i < 10 do
    print(i)
    i = i + 1
end

while, ( ).

+4

/ ; :


, 1, , for i = start , end , step do … end, for i = 1, 10, 3 do … for i = 10, 1, -1 do …. , .


"" while -loops , , . :

local diff = 0
for i = 1, n do
   i = i+diff
   if i > n then  break  end
   -- code here
   -- and to change i for the next round, do something like
   if some_condition then
       diff = diff + 1  -- skip 1 forward
   end
end

That way you can't forget the increment i, and you still have the adjusted ione available in your code. Deltas are also stored in a separate variable, so checking for errors is quite simple. ( iauto-increments should work, any assignment ibelow the first line of the loop body is an error, check if you are assigned diff, check the branches, ...)

+1
source

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


All Articles