[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: The new (5.0) for syntax
- From: Roberto Ierusalimschy <roberto@...>
- Date: Thu, 13 Jun 2002 09:34:17 -0300
> expList is a function which must return at least another function, and that
> can return a state (for persistance of data) and an initial value.
It doesn't need to be a function. It is an expList, so it can also be
two (or three) expressions. It is exactly the same as in a multiple
assignment:
a,b = f()
a,b = e1, e2
> I tried with the following code (also provided by Roberto):
> t = { "a", "b", "c" }
> for i, k in nexti(t) do print(i, k) end
> for k, v in next, t do print(k, v) end
> for k, v in t do print(k, v) end
> The results are identical. I am not sure to understand the second syntax
> (with 'next').
See previous remark. In the second syntax, you explicitly give the
iteration function (`next') and the state (`t'). The third syntax is
only a kind of syntactic sugar.
> It seems I cannot write "for k in next do ... end", Lua reports 'next' is
> expecting a parameter, but which one it gets in the above line?
According to your translation, uou are calling _func(_state, var1), where
_func=next, but _state=nil.
> It works fine, of course. I just don't understand the "and nil" part. Oh, I
> suppose it is to force the return of a nil value, since assert doesn't return
> anything.
Assert returns its argument (if it is not false); in the example this is
the result from f:close(). The "and nil" is to force the expression to be
nil (otherwise the `for' wouldn't stop).
> function lines(filename)
> local f = assert(io.open(filename, "r"))
> local state = {}
> state.persistentValue = " "
> state.counter = 0
> return function (_state, _previousValue)
> _state.persistentValue = "." .. _state.persistentValue
> _state.counter = _state.counter + 1
> print(_state.persistentValue .. _previousValue)
> return f:read() or (assert(f:close()) and nil), _state.counter
> end, state, "First value"
> end
>
> But I am no longer sure of the advantage of this state over the previous
> version...
> Well, it looks more like OO, and I am probably missing some side effect.
This is a matter of taste. The big advantage of using the state is when
you don't need to create any new "object" (table, closure, etc.) to run
the for. The `nexti' is an example.
In "heavier" loops, the cost of an extra object is negligible. E.g.,
in the file example, you already have to open the file, create a file
handler, create several strings (the lines), etc. etc. An extra closure
(or table) makes little difference to the total bill.
BTW, you should add your explanation into the Wiki.
-- Roberto