lua-users home
lua-l archive

Re: Proxy tables

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


> Note that the problems iterating proxy tables are also an issue for
> the lazy-copy approach to copying tables.
The question here is if a lazy-copy table iteration should copy all iterated
values. If so, then that's a bit tricky. If not then the iterator cpairs
defined below could be used. (Of course, being used to lua 4 I forgot all
the necessary explicit == nil and ~= nil tests first... :-) )
do
 local copies = {}
 setmetatable(copies, {__mode = "k"})
 local meta = {
 __index = function(table, index)
 local t = copies[table]
 local v = t[index]
 table[index] = v
 return v
 end,
 }
 function copy(table)
 local c = setmetatable({}, meta)
 copies[c] = table
 return c
 end
 function cnext(table, index)
 local v
 if index == nil or rawget(table, index) ~= nil then
 index, v = next(table, index)
 if index ~= nil then return index, v end
 end
 local t = copies[table]
 repeat
 index, v = next(t, index)
 until index == nil or rawget(table, index) == nil
 return index, v
 end
 function cpairs(table)
 return cnext, table
 end
end
local x = {aap=1, noot=2, mies=3, zus=5}
local y = copy(x)
print(y.noot, y.zus)
for k, v in cpairs(y) do print(k, v) end
--
Wim

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