lua-users home
lua-l archive

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


I'm also confused about the need for pairs/ipairs metamethods.  Has
anyone considered going in the other direction (design-wise), which is
to:

(1) acknowledge that pairs/ipairs pertain only to tables (several
people have done this already); and
(2) as a result of this observation, move pairs/ipairs into the table library.

The generic 'for' loop in Lua is so elegant that I would encourage its
use by highlighting the fact that pairs/ipairs are just two iterators
for tables.  Tables can have other iterators over keys and values, and
other objects can have their own iterators over whatever is
appropriate.

The iterator expression in the 'for' loop should return a stateful
iterator function.  If you are using an OO style, you will probably
call a method to create and return a stateful iterator.  (Note that
the parentheses are required and good.  It should be clear that a
method is being called.)

Anyone can add a function ("each" and "values" have been proposed)
that accepts an object and calls the object's __iter metamethod by
convention.  The name "values" and the name "__iter" do not have to be
fixed in the Lua language.  Neither do "pairs"/"ipairs" (which could
belong to the table library) or "__pairs"/"__ipairs" (which I think
are not needed).

Jim