lua-users home
lua-l archive

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


I don't get the point of those iterators either, but one possible argument for the operators would be external libraries taking in external objects using pairs or ipairs on them. Maybe I see pairs and ipairs as utility functions and not part of the syntax.

I think an operator like this would make more sense (although I probably wouldn't use it personally)

    local meta = {}
    meta.__index = meta

    function meta:__iterator(a, ...)
        local i = 0
        return function()
            i = i + 1
            return self.foo[i] + a
        end
    end

    local obj = setmetatable({}, meta)

    obj.foo = {1,2,3,4,5}

    for res in obj, 10 do
        print(res)
    end

    >>11
    >>12
    >>13
    >>14
    >>15
    >>16

On Fri, Mar 16, 2018 at 11:56 AM, John Hind <john.hind@zen.co.uk> wrote:

>>>> for i,v in pairs(t) do print(i,v) end

>>A perfect example of why deprecating __ipairs was the wrong move. It
>>ought to be possible to make this code work with ipairs(t) as well, but
>>with no __ipairs metamethod it can't be done.

>>Andrew.
Except of course by the simple expedient of replacing ipairs(t) with a version
that does what you want it to do directly! Even, if you insist, with a version that
uses a metamethod __ipairs! The metamethods on both pairs and ipairs have
always baffled me with their utter triviality!

- John.