lua-users home
lua-l archive

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


I think the real reason why 'for k,v in t' is deprecated is that it's
both ambiguous and slow. At compile time it is not clear whether t is
a table or a function. Therefore a (slow) runtime check in the form of an
extra VM instruction (OP_TFORPREP) is needed for _every_ iterator loop.

And there's an implicit lookup of 'next' in the global table, too
(which is ugly from a VM design standpoint).

Whenever this compatibility check is gone, you can still write
'for k,v in obj' provided you add a __call metamethod to the table
(or userdata). Providing a default (implicit) __call metamethod for
plain tables may be an interesting way to solve the compatibility problem
(alas, one side-effect is that _all_ tables are then callable objects, too).

The other argument is that most containers do not have just a single
iterator. There are two standard iterators for plain tables and more could
be conceived. And complex objects may provide dozens of iterators ...
So which one do you expect to be used when you write 'for i in obj'?
Which one do the readers of your code expect to be used?

Going with 'explicit is better than implicit', it's just good programming
practice to spell out _which_ iterator you want to use. Remember that
your code is much more often read than written. Therefore it is more
important to convey your intentions clearly than to save a few keystrokes.

BTW: The proxy-table problem is really orthogonal to the above problem.
You really want to be able to use the same 'way' to iterate over plain
tables and proxy tables. But this does not imply that we need syntactic
sugar for this. A function or method may solve this just as well (as has
been shown).