lua-users home
lua-l archive

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


> I stumbled across needing to do this in order to catch __newindex
> operations. The problem with this is that it then breaks things like
> table iteration. Any advice on how to make this work?

That depends, of course, on your implementation.  You probably need to
define your own iterator (also called "generator") to support for loops.
See the "for ... in ..." statement described in

    http://www.lua.org/manual/5.0/manual.html#2.4.5

If your proxied tables should blend in with ordinary tables then I think you
must redefine the global "pairs" function or --better still-- the "next"
function.  (It was suggested on this list to make __pairs a meta method that
can be used by pairs, but this is not currently the case.)

Here's a (too) simple example:

do
    local signature = {}

    -- set a proxy on table
    function proxy(table)
        local meta = {
            __index = table,
            __newindex = function(_, index, value)
                    table[index] = value
                end,
            __signature = signature,
        }

        return setmetatable({}, meta)
    end

    local n = next

    -- next replacement to support pairs and "old style" for loops
    function next(table, index)
        local m = getmetatable(table)
        return n(m and m.__signature == signature and m.__index or table,
index)
    end
end

local x = {aap = 1, noot = 2}
local y = proxy(x)
y.mies = "vuur"

print(y.aap, y.noot, y.mies)

-- iterator style
for k, v in pairs(y) do print(k, v) end

-- old style
for k, v in y do print(k, v) end

-- this still works (not a proxy)
for k, v in pairs(x) do print(k, v) end
for k, v in x do print(k, v) end

-- table.foreach can't be tricked however...
table.foreach(y, print)


--
Wim