Search code examples
for-loopluainfinite-loop

Lua - changing 'stop' variable's value from within the for-loop, will it terminate as normal still?


For example, if I do the following:

local iStop = 32
for i = 1, iStop do
  iStop = iStop + 1
end

Will the loop be guaranteed to run only 32 iterations, or is there any case it may run infinitely?


Solution

  • Please refer to the Lua Reference Manual 3.3.5: For statement

     for v = e1, e2, e3 do block end
    

    is equivalent to the code:

     do
       local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3)
       if not (var and limit and step) then error() end
       var = var - step
       while true do
         var = var + step
         if (step >= 0 and var > limit) or (step < 0 and var < limit) then
           break
         end
         local v = var
         block
       end
     end
    

    ...

    All three control expressions are evaluated only once, before the loop starts.

    The loop will run 32 times. The actual loop limit is a copy of iStop's value befor the loop starts and no matter what you do to iStop in the loop it will not affect the loop limit.