lua-users home
lua-l archive

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


On Aug 19, 2014 5:34 AM, "David Demelier" <demelier.david@gmail.com> wrote:
>
>
> Le 02/08/2014 09:16, Dirk Laurie a écrit :
>
>> This subject is too important to be buried in the big thread.
>>
>> The idiom
>>
>>     for k,v in ipairs(tbl) do
>>
>> appears in numerous programs, very few of which are paranoid
>> enough to test (redundantly, up to now) that v is not nil. f you
>> explicitly supply __ipairs, you take responsibility, fair enough.
>>
>> Now __ipairs is deprecated (although still recognized with default
>> compatibility options) and that idiom is equivalent to
>
>
> Mmm, how can you use ipairs on a userdata if the metamethod __ipairs is removed ? Do you need to implement an __index function which verify if the index value is an integer?
>
> Regards,
> David.
>

This is a good point as well: removing __ipairs makes it harder to make a custom object which "pretends" to be a table. E.g. if I want to retrieve each value from a database as it's requested. With __ipairs I can pass my object to code which simply expects "some iterable object"; without, that code needs to know *how* to iterate every type of object it might receive.

I don't see a reason to remove __ipairs. It provides a common interface to iterate any object in order (whatever "in order" may mean for that object), just as __pairs provides a common interface to iterate a dictionary.

I've stated before that I'm a big fan of duck typing, and removing generic metamethods in favour of everyone providing their own interfaces makes that more difficult. My code shouldn't have to care whether it's iterating an array or a database or a file; it should just be able to say "give me the contents in numeric order, one at a time", which in Lua is written: ipairs(Foo)