lua-users home
lua-l archive

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


On Wed, 16 Sep 2009 08:43:56 -0300, Luiz Henrique de Figueiredo
<lhf@tecgraf.puc-rio.br> wrote:

> But tables are used to implement objects and those may want different behaviors.

I understand, and I'm suggesting that the object designer provide his
own iterator, even if that iterator is just an existing table
iterator.  This approach hides the implementation of the object a
little better.

E.g.
function makeVector(...)  . . . end
elements = ipairs

v = makeVector(1,2,3,4)
for e in elements(v) do print(e) end

Once you give your users pairs or ipairs as iterators for your object,
you are stuck forever with a particular implementation in which all of
the enumerable attributes correspond exactly to the table entries.

Since tables are intrinsic in Lua, it's essential to have the basic
table functions in the base language (including # and next).  And it's
easy to make the same case for pairs as well.

But perhaps the right "convenience" feature for objects should be an
iterator factory named 'values' or 'each' (as already suggested),
where the factory function runs the __iter metamethod on whatever
object it is given?   At least, then, everyone knows how to use the
"default iterator" for any object.

Objects can have other iterators, but you have to name them yourself
when you design your object.

If your object's implementation is a table, then setting __iter=pairs
or __iter=ipairs in the object's metatable will let you use your
choice of the built-in table iterators (via the proposed 'values' or
'each' iterator factory function) without having to expose the
(current) implementation of the object.

 Just my USD$0.02.

Jim