lua-users home
lua-l archive

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

For tables (or userdata) which do not work with standard pairs/ipairs
implementations, I prefer to add a __call metamethod to the table,
which acts like an iterator function:
function b_iterator(t, s, k)
    k = next(getmetatable(t).__index, k)
    return k, t[k]

a = {fruit='banana',state='qld'}
b = {state='nsw'}
setmetatable(b,{__index=a, __call = b_iterator})

for k,v in b do
   -- chunk

(not tested the above code, but you get the idea). This only works
with Lua 5.1 (as 5.0 will not treat tables as functions when given in
a generic for statement), and gives a slightly more natural syntax for


On 21/09/2007, Mark Hamburg <> wrote:
> This basically gets us back to the point that pairs should probably be
> redefined to look for a __pairs metamethod.
> This might make sense for ipairs as well though that case could also be
> addressed by using an integer indexed get in place of the lua_rawgeti. For
> efficiency, it might be necessary to introduce lua_geti.
> For efficiency reasons, it seems less appealing to introduce a metamethod
> for next.
> Mark