lua-users home
lua-l archive

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



Why so complicated?

I must be missing something, since isn't 'next()' just an implementation detail of 'pairs' and 'ipairs'. I mean, if I want to redefine those to actually support '__[i]pairs' metamethods, wouldn't this be sufficient:

    pairs = function( t )
        local mt = getmetatable( t )
        return ( ( mt and mt.__pairs ) or raw_pairs )( t )
    end

    ipairs = function( t )
        local mt = getmetatable( t )
        return ( ( mt and mt.__ipairs ) or raw_ipairs )( t )
    end



4.2.2005 kello 02:26, Mark Hamburg kirjoitti:

 I'm not sure I've seen a concrete proposal, so here goes:

    local raw_next = next
    local raw_ipairs = ipairs

    pairs = function( t )
        local mt = getmetatable( t )
        local mt_pairs = mt and mt.__pairs
        if mt_pairs then
            return mt_pairs( t )
        else
            mt_next = ( mt and mt.__next ) or raw_next
            return mt_next, t
        end
    end

    next = function( t, k )
        local mt = getmetatable( t )
        local next_imp = ( mt and mt.__next ) or raw_next
        return next_imp( t, k )
    end

    ipairs = function( t )
        local mt = getmetatable( t )
        return ( ( mt and mt.__ipairs ) or raw_ipairs )( t )
    end

This actually needs to be C code so that it can see protected metatables.

It's a little ugly having to patch both __pairs and __next, but so it goes.

In fact, one could argue that all of the standard table manipulation
routines should support this approach with the old versions potentially
exported in a rawtable namespace. So, consider the point argued.

The argument for adding these metamethods is that they work in support of
Lua's use of proxy tables.

Is there a strong against adding these metamethods?

I do go both ways on whether to export all of the raw routines. In
particular, pairs and table.foreach can be used to discover keys that one
might want to keep undiscoverable.

Mark