lua-users home
lua-l archive

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


On Fri, 15 Feb 2002, Tom Wrensch wrote:

> For example, I've always disliked having to do the for i=1,getn(t)...
> business to iterate through a "array" style table.
>
> [...]
>
> But now a simple generic iteration function can be defined:
>
>     function indexiter(tab)
>         local i=0
>         return function()
>             i=i+1
>             if i<=getn(tab)
>                 return i,tab[i]
>             end
>         end
>     end

Usually you don't need the counter in this case, only the values. And
usually you can stop in the first nil (maybe we should change the semantics
of getn, anyway?). Then your iterator gets more simpler:

    function indexiter(tab)
        local i=0
        return function()
            i=i+1
            return tab[i]
        end
    end

    t = {"now", "is", "the", "time"}

    for v in indexiter(t) do print(v) end


> Likewise an iterator for the lines of text in a file can be created:
> [...]

If you want to read from stdin, "read" itself is an iterator!

  for line in read do print(line) end


> Other iterators can be built for reading files by word or character.
>
> In short his feature is seriously cool.

We agree ;-)

-- Roberto