lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Lars:

On Mon, 12 Dec 2022 at 12:06, Lars Müller <appgurulars@gmx.de> wrote:
> The current behavior in PUC Lua seems to be that modifying the loop control variable has no effect on the loop. I would not be surprised if LuaJIT was to apply optimizations that leverage the fact that you may not modify the loop control variable. Ideally the Lua compiler should emit a warning when it encounters modifications of the loop control variable. If you really need to modify the loop control variable, just create a local copy, which is more explicit, to spec and thus guaranteed to work, and just costs nothing but one line of code:
> for i = 1, 10 do
>      local i = i
>      i = i + 42 -- perfectly fine
>      print(i)
> end

This does not MODIFY the loop control variable. It only lets you have
another one...

> You can avoid shadowing the loop control variable (which linters like Luacheck don't like) by rename one of the two variables.

... as you clearly state. If you NEED to modify the loop control
variable just byte the bullet:

do
   local i=1
   while i<=10 do
      Whatever_you_want()
      Whatever_you_like()
      Whatever_you say()
      You_pay_your money()
      You_take_your_choice()
      i=i+1
  end
end

Francisco Olarte.