Look at the following code:
for i=1,2 do
print(i)
i=3
end
What is the output? If you are used to C/C++ language, you will feel that because the control variable i is changed to 3, it is judged that it will not pass before executing the second loop body, so the output is 1.
But the result output is 1 and 2, that is, although i is changed, the loop is still executed twice. Why is this?
After looking at the source code of lua, I found that in the syntax analysis stage, the i in the expression (also called a control variable) and the i in the loop body are not the same value. In fact, the i in the expression is called internal index, and the i in the loop body is called external index.
Therefore, the value of i in the expression is not changed in the loop body.
As for why lua does this, it is probably for safety, for fear that the i of the expression will be changed inadvertently in the loop body, resulting in a bug.
In addition, in the book Progamming in Lua, it is also mentioned that the value of the control variable (the actual modified external index) should not be modified in the loop body, otherwise there will be unpredictable results.