lua-users home
lua-l archive

Re: __iter metamethod?

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


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
 function iterator()
 i = i + 1
 return i
 end
 for a in iterator do
 print(a)
 end
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.)
--
David Given
dg@cowlark.com

AltStyle によって変換されたページ (->オリジナル) /