lua-users home
lua-l archive

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


gary ng <garyng2000 <at> yahoo.com> writes:

> I am wondering if this is possible. That is I want a
> table which refers to another table if it doesn't have
> the particular key and any write does not touch its
> prototype. 

-- Here's one way to do it:

function getShadowTable (t)
    local mt = {}
    function mt:__index (k)
        local v = t[k]
        if type(v) ~= "table" then return v end
        local shadow = getShadowTable(v)
        self[k] = shadow
        return shadow
    end
    return setmetatable({}, mt)
end

-- It passes your requirements...

t1 = { a = 1, b = {} }
t2 = getShadowTable(t1)

t1.b.a = 1
assert(t2.b.a == 1)
t2.b.a = 2
assert(t1.b.a == 1)
assert(t2.b.a == 2)

-- But there are problems if t1.b is replaced after t2.b is read.
-- That may not arise in your application...

t1 = { a = 1, b = {} }
t2 = getShadowTable(t1)

t1.b.a = 1
assert(t2.b.a == 1)
t1.b = { x = 2 }
assert(t2.b.x == 2)     -- assertion fails