lua-users home
lua-l archive

Re: __pairs metamethod - is it in?

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


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

AltStyle によって変換されたページ (->オリジナル) /