lua-users home
lua-l archive

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


On Wed, Jun 10, 2009 at 2:16 PM, John Hind<john.hind@zen.co.uk> wrote:
> Ugg! Not a good choice, in my opinion! There is a "right choice" of iterator
> for different types of object and it should be contextually selected not
> having to remember whether to use pairs or ipairs. If you go down this way,
> we'll end up defining __pairs or __ipairs to give error messages if the
> wrong one is used! This is like saying the user has to use a different
> function for adding real and complex numbers and if they pick the wrong one
> they'll get a result, but a meaningless one.
pairs and ipairs are "intended" for iterating over table-like objects.
__pairs and __ipairs allow non-tables to behave like tables do in more
situations. If you want to attach them to a more complex object, then
simply set __pairs and __ipairs to the same function if you want to
make pairs() and ipairs() both do the default iteration. For complex
objects, it may not be obvious (to people other than the library
author) what the default iteration is. In this case, it can be clearer
if the complex object has members on it for iteration, like "for k,v
in obj:children() do" or "for callback in obj:callbacks() do", thus
making it explicit what part of the object is being iterated.

On Wed, Jun 10, 2009 at 2:16 PM, John Hind<john.hind@zen.co.uk> wrote:
> I cannot see why this is syntactically impossible. Just check first for a
> __iter when parsing the for statement, if not present, fall back to
> processing as currently.

The parser doesn't know what type of value "t" is in "for k, v in t
do", let alone if it has an __iter metamethod or not.