lua-users home
lua-l archive

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

Is it OK to do things like this:

for k,v in ipairs{10,20,30,40} do
    if k==3 then k = 1 end  -- pointless but keeps the example small
    ...other stuff that processes k,v...

I _know_ this doesn't rewind the iteration at all; that's not my intent.
Sometimes it's just useful for the logic of the loop body to reassign
the control variable.

Similarly, what about:

for i=1,10 do
    if i==3 then i = 1 end
    ...other stuff that processes i...

Again, I _know_ it doesn't rewind the iteration. The question is just,
do we _have to_ keep our hands off of the control variable?

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...
The generic loop [my first example, above] shares two properties with
the numeric loop: the loop variables are local to the loop body and you
should never assign any value to them."

But if you look at the code equivalents in the reference manual:

> for var_1, ···, var_n in explist do block end
> is equivalent to the code:
> do
>     local f, s, var = explist
>     while true do
>         local var_1, ···, var_n = f(s, var)
>         var = var_1
>         if var == nil then break end
>         block
>     end
> end
> 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
>     while (step > 0 and var <= limit) or (step <= 0 and var >= limit) do
>         local v = var
>         block
>         var = var + step
>     end
> end

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. And simple tests in the interpreter don't show anything funny happening...

I assume that PiL knows what it's talking about :-) but why do the different sources of documentation not give a consistent message?