[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: __iter metamethod?
- From: David Given <dg@...>
- Date: Tue, 09 Oct 2007 10:45:13 +0100
steve donovan wrote:
for i,v in t do
In this context, 'for' expects t to be a callable thing. Normally this
is a function, as the first parameter of a tuple:
for k, v in ipairs(table) do
=> for k, v in fn, table, 0 do
'for' then calls fn repeatedly to fetch the values, passing in the rest
of the tuple (which gets modified during the iteration).
The problem is, the rest of the tuple is *optional*. It's perfectly
possible to use an iterator function without them.
i = 0
i = i + 1
for a in iterator do
And, of course, tables can be overridden using the __call metatable
entry to look like functions.
The upshot of this is, if you add an __iter metatable entry to allow
iteration on tables, you also add a nasty ambiguity as to what happens
if the table has both a __call *and* an __iter. That's not to say it
can't be done... just that ambiguities like this are best avoided if you
wish to retain your sanity.
(And implementing iteration using __call is tricky because you don't get
told when the iteration starts or stops. Note that my iterator function
above uses *global* state, not a per-invocation state.)