lua-users home
lua-l archive

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


RLake:
>> My original thought was a __next metamethod. But after I tried writing a
>> few of them, I decided that __pairs is actually a lot easier to
implement
>> in many interesting cases. Try a few and see for yourself...

Peter Hill:

> I don't understand...?

> Have you got a couple of your examples?

Take a look at the code I wrote in my original response to this message.
Here, __pairs creates a next function closed with two upvalues, which
retain the state of the iteration.

That is a general problem with iterations which require retained state. The
only state a __next metamethod would have is the key itself, and it is
undesirable to overload the key with internal state information because it
is exposed to user code (and also it is quite useful that it be a key, and
not a state description.)

This could be solved by changing the definition of the "for k, v in next,
state, initial-key" statement in order to pass and return the state to the
next function each time, as well as the iterated object and the key. That
would arguably be a reasonable solution but I don't think anyone wants to
change the for statement yet again.

If you can come up with a __next metamethod that would work in this case,
let me know.