[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Numeric for loop: Changing control variable REALLY dangerous?
- From: Sean Conner <sean@...>
- Date: Sat, 10 Dec 2022 02:47:40 -0500
It was thus said that the Great bil til once stated:
> In chapter 3.3.5, there is a bit a "strange sounding" warning:
> "You should not change the value of the control variable during the loop."
>
> ... is this not a bit "over-cautious"?
>
> e. g. in a typical loop "for i=1,count do ... end", it is quite often
> really useful to repeat a loop sequence by "i=i-1", or to repeat
> complete loop by "i=1" assignment.
>
> This REALLY can be dangerous? (or can give anybody possibly give some
> illegal / "bad-running" example for such change?)
I tried it, in Lua 5.1, 5.2, 5.3, 5,4 and LuaJIT 2.0:
local count = 10
for i = 1 , count do
print(i,count)
if i == 3 then
i = nil
count = nil
print(">",i)
end
end
print("<",count)
They all behaved the same way, and it appears to work like this:
local count = 10
do
local _Unnamed_value = 1
local _Unnamed_limit = count
local _Unnamed_step = 1
while _Unnamed_value <= _Unnamed_limit do
i = _Unmamed_value
--
-- body of loop
--
_Unnamed_value = _Unnamed_value + _Unnamed_step
end
end
I suspect the warning is there because changing the control variable
doesn't work as one might expect, and not to rely upon changing either the
control variable, or the limit variable.
-spc