lua-users home
lua-l archive

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


2016-06-24 10:00 GMT+02:00 Duane Leslie <parakleta@darkreality.org>:

> Would it be possible to add a `__next` metamethod to allow the `pairs`
> behaviour to be inferred in the same way that now the `ipairs`
> behaviour is inferred from the `__index` metamethod.  I have looked
> through some discussions of this in the mailing list in the past and
> it seems to have been that the `__pairs` metamethod was preferred
> because it was more powerful (it allows the construction of a `next`
> equivalent function as a closure with additional information).
>
> The problem I have is that I have situations where the `next()`
> function makes more sense to iterate over some userdata objects than
> using `for ... pairs` but I cannot make the behaviour of these two
> methods equivalent.
>
> The idea would be to have the situation where I could define just the
> `__next` metamethod, and this would be used as the result of the call
> to the `next` function, and so in turn would imply that `pairs` would
> call my `__next` metamethod through the standard `next` function.

Well, actually all that 'pairs(tbl)' does is to return 'next,tbl,nil', but
it does so in C, which is ever so much nicer. So all you need is:

   for k,v in mynext,tbl do ...