问题
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? :)
回答1:
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.
回答2:
What about using a while(true)
loop instead? Then you'll have to break manually, but that might work.
local i = 5
while(true) do
print(i)
i = i - 1
if (i == 0) then break; end
end
回答3:
Attempting to set the loop control variable causes a failsafe behavior.
I can't find it in the Language Incompatibility section of recent versions of the manual but I recall it being listed somewhere as a change. It was more of a formalization of previous undefined behavior.
If you are really curious, see the listing of your program from luac
. The loop control variable is given an internal name so it can't be changed. If the same name is used in an assignment, a local variable is synthesized as a stand-in. It prevents unintentionally causing the for
to become infinite.
You need another kind of loop.
来源:https://stackoverflow.com/questions/29777255/lua-for-loop-reduce-i-weird-behavior