[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Reassigning control variables in loop body?
- From: David Manura <dm.lua@...>
- Date: Wed, 4 Nov 2009 21:28:18 -0500
On Tue, Nov 3, 2009 at 8:55 AM, Jim Pryor wrote:
> PiL 2nd ed, pp. 32 - 33 say:
> "You should never change the value of the control variable [in examples
> like the second, above]: the effect of such changes is unpredictable..."
> But if you look at the code equivalents in the reference manual:....
> The control variable is supposedly saved in a hidden variable "var" that isn't
> exposed to the programmer. So it should be harmless for the programmer to
> overwrite var_1 in the first statement, or v in the second statement.
Maybe the statement was a carryover from the first edition covering
5.0. PiL's opinion doesn't matter though: only the Reference Manual
defines specified behavior. The Lua 5.0 Reference Manual omits this
hidden variable and explicitly says "The behavior is undefined if you
assign to var inside the block."  As you saw, the Lua 5.1
Reference Manual seems to allow this. A change was made between
That said, what's permissible is not always beneficial. That fact
that you're unsure indicates that others reading your code are likely
unsure as well. You can for greater code clarity rewrite it in a way
that avoids mutating variables: "local j = (k==3) and 1 or k"
(recommended) or, if you really want, "local k = (k==3) and 1 or k".
Or rewrite as a while loop.