lua-users home
lua-l archive

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


I've been having a look through the Lua5.0(beta) documentation and noticed
the new general "for" statement. What I want to know is why the "pair"
function exists?

Ie, why do we write:
    a = {"alpha", "beta"}
    for i,v = pair(a) do print(v) end

Wouldn't it be just as fine to say:
    a = {"alpha", "beta"}
    for i,v = next,a do print(v) end

The above should be just the same as as the internal assignments:
    _f, _s, i, v = pair(a)
and
    _f, _s, i, v = next, a

----

Which brings up a separate issue regarding the exp/exp1 situation. If I
wanted to specify the initial index value in a "for" how would I? Surely:
    for i,v = pair(a),123 do print(v) end

would fail because, as a non-terminal in the assignment, "pair()" would be
chopped down to a single return value, effectively becoming:
    _f, _s, i, v = next, 123

rather than the desired:
    _f, _s, i, v = next, a, 123

I'm sure some way of allowing non-terminal exp (vs exp1) has been mentioned
before (no doubt ad-nausem) but in a case like this how does one get by
without it?

The generally solution would be to have some sort of return-value compiler
directive. Eg, let's use "#" (being the "number" sign) which we define as:
    n # f() -- truncate (or expand with "nil") to n values.
    # f() -- use all return values
    f() -- use one return value... same as 1#f()

Thus, my problem above would become:
    for i,v = #pair(a),123 do print(v) end

Note that I would probably also like to redefine the default assignment &
parameter expressions to be "[exp1 {,exp1}]" rather than the current "[[exp1
{,exp1}] exp]". Ie, ALL functions (terminal or non-terminal) are trimmed to
one return value, regardless of position, unless explicity specified
otherwise.

True, it's not compatible with the current method... but it's a lot clearer
and fairly easy to adjust code to. Otoh, one could always add a global
variable in Lua to specify which default one wants, eg "_TERMINAL_EXP =
true".

*cheers*
Peter Hill.