lua-users home
lua-l archive

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


On Mon, 24 May 2010 16:38:56 -0700
"Stuart P. Bentley" <stuart@testtrack4.com> wrote:

> Depending on how common iterator factories like pairs() are (especially  
> among the metatable-using crowd), this proposal might make more sense:
> 
>         --proposed addition
>         if type(f)~= "function" then
>           local meta_factory = metatable(f).__iter
>           if not meta_factory and type(f)=="table" then meta_factory =  
> pairs end
>           if meta_factory then f, s, var = meta_factory(f) end
>         end

Yes, the first version was OK, I guess; but this one is even clearer, by showing pairs() is just the standard version of iterator factory.


Denis


PS: Just to compare:

For a toy language project, I introduced the notion of traversal object for traversal loops (foreach). A traversal thing must have a 'start' method to store or setup parameter data, and a 'next' method to produce every item. Traversal objects can be used to traverse enumerated collections (iterator) or defined series (generator). Below 2 examples (untested!).
grammar:
   There is a strict distinction between actions & functions.
   '@' denotes the current object (this, self).
   '#' is the operator returning an item from an index (getItem).

Here is how to traverse a sequence in reverse order:

Reverse : Type
    start : action(sequence)
        @.sequence : sequence
        @.index : sequence.count
    next : function
        if @.index > 0
            item : @.sequence#@.index
            @.index :: @.index - 1
            item

Here is how to generate the cubes of integers in a given interval:

Cubes : Type
    start : action(interval)
        @.number : interval.first
        @.last : interval.last
   next : function
        if @.number <= @.last
            cube : @.number ^ 3
            @.number :: @.number + 1
            cube

Any kind of traversal can be defined as "function" method in custom collections or collection types, provided the result object does the job. By default, the language looks for a method called 'traversal'. Traversals would be used as expected, I guess ('!' is the "execute" operator):
    foreach item in myColl		' default 'traversal' method
    foreach item in Reverse(myColl)!    ' externally defined
    foreach item in myColl.reverse!     ' defined on myColl or its type
    foreach cube in Cubes(3,9)!

________________________________

vit esse estrany ☣

spir.wikidot.com