lua-users home
lua-l archive

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



On 1-Sep-05, at 11:19 AM, Mark Hamburg wrote:

I've been contemplating whether Lua needs:

    function argforeach( fn, ... )
        for I = 1, select( "#", ... ) do
            fn( ( select( I, ... ) ) )
        end
    end

This should be written in C to avoid the performance issues cited above and
probably needs a better name.

A simpler and possibly more general one would be:

  for i, v in eachi(<list of values>) do

which you could call:

  for i, v in eachi(...) do

but it does require copying the ... several times.

As an aside, this is one of the (several) reasons I personally would have prefered built-in tuples, with the varargs syntax creating a tuple instead of a table. While this is not as fast as the magic ... solution in some simple use cases, the additional power makes it considerably faster in a variety of other use cases, including iterating over parameter lists, and it is considerably faster than varargs creating a table. (Tuples also allow a neat way of capturing multiple return values, and a way of using varargs as an upvalue.)

An alternative would be to extend the syntax to define:

    for i, v in ... Do
        -- do stuff with the i-th element of ...
    end

So that it implements the appropriate loop. This means that if you want to pass iteration parameters via ..., then you will need to bind them to locals
outside of the loop or use select( 1, ... ) in the loop.

ick. Sorry. More magic to the magic ...

P.S. The absence of standard support for packing and unpacking argument
lists containing nil is an annoyance.

Agreed. (cough, cough, tuples would solve that issue too)