lua-users home
lua-l archive

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


On Fri, Aug 1, 2014 at 9:49 AM, Tim Hill <drtimhill@gmail.com> wrote:

> I’m a bit surprised, however, that __ipairs() was deprecated. I see no reason why you can’t have both __ipairs() and respect metamethods; ipairs() simply defers to __ipairs() for the whole iteration if found, while otherwise using it’s default behavior and respecting __index() etc.

I was never a big fan of __pairs but I'm glad it was there.  99% of
the time I was just doing __pairs = function () return
ipairs(other_table) end  -- because I was proxying to the real table
to iterate over.

The 1% is what always frustrated me.  This is when I would be exposing
an object from C to Lua and I needed a way to hand ipairs() the keys
so it could iterate over each pair in the C object, using the __index
I had set up.

I've always liked the idea of __next better because the function in
that 1% case would look similar to:

local ckeys = { 'a', 'b', 'c', 'd', 'e' }

__next = function (self, key)
    local ckeys_idx = indexOf(ckeys, key) or 1
    return ckeys[indexOf(ckeys, key) + 1]
end

Now, I've been up for a large number of hours so I'm probably missing
something here.  I just find it pretty frustrating to write the
iterator for __pairs to "zip" together the ckeys and index from the C
object that's been exposed.  Perhaps I'm wrong and there is a simpler
way.  I'm sure I'll regret this post later :p  The consequence is it's
no longer easy to proxy to other tables like it is with __ipairs, so
this is why I thought having both would be useful.  ...and __type, and
__tonumber, and ....