lua-users home
lua-l archive

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


Alex,
Thanks, but I am looking for some version where cow on tables is either default or can be enabled under a switch.
Cynthia.



On Tue, Feb 21, 2012 at 1:56 PM, Axel Kittenberger <axkibe@gmail.com> wrote:
This needs Lua 5.2, with 5.1 or LuaJIT you're mostly out of luck (as
far I know). Also note this will make a copy of original at the moment
of write, not of the moment made the COW, so if you change the
original before, it changes in background. But I suppose you consider
that one immutable.

function makeCOW(o)
   return setmetatable({}, {
       __index= o,
       __pairs = function() return pairs(o) end,
       __ipairs = function() return ipairs(o) end,
       __newindex =
           function(t, k, v)
               setmetatable(t, nil)
               for ck, cv in pairs(o) do t[ck] = cv end
               t[k] = v
           end,
   })
end

local org = {1,2,3,4,5,6,7,8,9}
local cpy = makeCOW(org);

for k, v in ipairs(cpy) do print(k, v) end
print('----')
cpy[2] = 5
for k, v in ipairs(cpy) do print(k, v) end