[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: COW(copy on write) table which contains table element ?
- From: Bret Victor <bret@...>
- Date: Fri, 16 Mar 2007 04:10:15 +0000 (UTC)
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