lua-users home
lua-l archive

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


On 16 March 2018 at 12:44, Peter Aronoff <telemachus@arpinum.org> wrote:
> John Hind <john.hind@zen.co.uk> wrote:
>> pairs and ipairs were never supposed to be syntax, they are one of any
>> number of possible implementations of iteration which were intended to be
>> extended by users and library authors.
>
> I’m sorry, but just to be clear: are you saying that every module author
> should create their own custom iteration? That seems like a huge stretch,
> even if we all agree that it’s a strength of Lua that you *can* easily
> write your own custom iterators.

As a Lua user, this is what I expect from pairs and ipairs:

* pairs - for an indexable value (i.e. some v I can do v[x] on), give
me all possible x's, and their v[x]'s, with no order guarantees.
* ipairs - for an integer-indexable value (i.e. some v I can do v[i]
on), give me all values from v[1] up in order, breaking at the first
nil.

If I can make my custom object (metatable-powered userdata or
whatever) respect these two protocols, I'll make them pairs() and
ipairs() usable for them via metamethods. If I want any other behavior
(restricting or relaxing the above protocols), I will provide a
separate iterator.

For example: I'll use a sortedpairs() iterator instead of adding to a
table a __pairs metamethod that always returns keys in sorted order.
It's easier for whoever is reading the code.

Another example: one time when I bridged Java collections into Lua, I
gave users an each() iterator for iterating Java Vectors (that
returned only values and no keys), instead of making pairs() return
sorted elements or making ipairs() return a zero-based iteration (or
worse, returned different indices for values on the Lua and Java
sides).

-- Hisham