lua-users home
lua-l archive

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


This is a "knarly" area of Lua. Strictly speaking only 'next' and 'pairs'
apply to tables. 'ipairs' and the entire contents of the 'table' library
apply to a specialised form of 'table' which would be better called 'array'
or 'list'. Because Lua does is not object oriented (but provides the tools
for users to make it object oriented) this specialisation is done informally
by just having rules about how the table indexes are handled.

In my view, while the generic for is very flexible, it does not read well:

for v in something do ... end

Just from the ordinary meaning of the keywords (let alone expectations from
other languages with similar constructs) most beginners would expect
'something' to be the table itself, not a function call which returns a
function, a table and nil!

Your own use of language (and my own long-standing misunderstanding of the
exact operation of the '__call' trick) illustrates the counter-intuitive
nature of this very subtle system: 'pairs' and 'ipairs' are not iterators,
'next' is the iterator. 'pairs' and 'ipairs' are 'iterator factories'. You
can write '__call' as an iterator factory (in which case it has to be called
with empty parenthesis) or you can make it an iterator (in which case the
parenthesis must be omitted)!


> -----Original Message-----
> From: lua-bounces@bazar2.conectiva.com.br [mailto:lua-
> bounces@bazar2.conectiva.com.br] On Behalf Of Jim Jennings
> Sent: 16 September 2009 12:26
> To: lua@bazar2.conectiva.com.br
> Subject: Re: First class : (was Re: Regarding the name 'pairs')
> 
> 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