lua-users home
lua-l archive

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


On 17/12/2009, at 10:29 AM, John Hind wrote:

> No! You cannot implement '__iter' by re-writing pairs and ipairs, that is
> the competing (and I agree , trivial) '__pairs' & '__ipairs' proposal which
> provide metatable customisation of pairs and ipairs similar to the way
> '__tostring' customises the "tostring" function.
> 
> '__iter' is intended to enable you to write:
> 
> for v in obj do ... end
> 
> Where 'obj' is a table with a metatable containing a function similar to
> 'pairs' keyed with '__iter'. You have to modify the parser and probably the
> byte code interpreter to implement this.


Ok, I misunderstood.  To see if I'm now on the right track, am I right in thinking that:

for v in obj do ... end

iterates through obj's "default" list, in a default order and only ever provides one value to the iteration?

I can see where you're coming from in terms of simple syntax, but that's a fairly constrained interface and I tend to find that I need things like:

for v, u, w in obj:give_me_several_values() do ... end
for v in obj:choose_an_order() do ... end
for v in obj:choose_a_set_of_elements() do ... end

If you're worried about polluting the object's namespace, is a syntax like

for v in elements(obj) do ... end

really too ugly?


Cheers,
Geoff