Comment by ksymph

Comment by ksymph 15 hours ago

3 replies

> for-loop variables are read only

Seems like an odd change, I wonder what the rationale is. Just making it clear to people new to the language that you can't adjust it mid-loop to change the loop count I guess?

pvitz 15 hours ago

From the manual:

   The control variable in for loops is read only. If you need to change it, declare a local variable with the same name in the loop body.
Also [0]: Roberto Ierusalimschy > So what's the rationale to make them constant now? Does it have performance > reasons?

Yes. The old code does an implicit "local x = x" for all loops, in case you modify 'x'. With the new semantics, the code only does it when you ask for it.

[0] https://groups.google.com/g/lua-l/c/SlAG5QfpTac

ufo 14 hours ago

That was already the case in previous versions of Lua. You could assign to the loop variable but the assignment would be overwritten in the next loop iteration.

https://www.lua.org/manual/5.3/manual.html#3.3.5

The loop count was fixed at the start of the loop. One of the reasons for this was performance. For loops behave differently if the step count is positive or negative, and it's a bit faster to compute that once, before the loop, than to repeat it every iteration.

GranPC 15 hours ago

In previous versions, you could change it mid-loop. This apparently caused some unintuitive behavior when paired with generators (e.g. `for k, v in pairs(table)`).

I haven't run into this myself, but it does make sense, and eliminating this footgun sounds like a good idea.