lua-users home
lua-l archive

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


Yes but like all metatables, you attach the right one to the right object,
so dictionary-like tables get a metatable with a pairs-like __iter
implementation while list-like tables get a metatable with an ipairs-like
__iter. You cannot really have a generic metatable for the base-Lua table
like you can for string. Most of the table library only applies to list-like
or array-like tables rather than dictionary-like ones.

We seem to be using terminology slightly differently, but if you wanted to
call the metatable key "__gen" or even "__for" (or "__in"?) I would not
object. Either way it would supply the thing that goes between the 'in' and
the 'do' in Generic For (which you call a generator?).

-----Original Message-----
From: lua-bounces@bazar2.conectiva.com.br
[mailto:lua-bounces@bazar2.conectiva.com.br] On Behalf Of Roberto
Ierusalimschy
Sent: 16 December 2009 18:01
To: Lua list
Subject: Re: '__iter', yet again!

> I am in two minds between table.foreach and Generic For with __iter, but I
> find Generic For without __iter to be a rather half-assed implementation!

table.foreach allows different iterations over a table (e.g.,
table.foreachi), while __iter does not.

About the choice between iterators (table.foreach) and generators
(pairs(table)): iterators are easier to write but generators are
more flexible to use. (See the famous "same fringe problem".)

Coroutines make trivial to convert an iterator into a generator, so we
can have the best of both worlds: you write an iterator and use it as
a generator. So, Lua favors the use of generators, through the generic
for.

-- Roberto