Skip to content

Instantly share code, notes, and snippets.

@stuartpb
Created May 25, 2011 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuartpb/991174 to your computer and use it in GitHub Desktop.
Save stuartpb/991174 to your computer and use it in GitHub Desktop.
Monstrous one-size-fits-all Lua table copy
return function (t,o)
local refs = {}
local rk, rv
if type(o.recurse) == "string" then
if string.find(o.recurse,'k') then
rk = true end
if string.find(o.recurse,'v') then
rv = true end
elseif o.recurse then
rk=true; rv=true
end
local mt = o.metatables
local getmetatable = o.getmetatable or getmetatable
local setmetatable = o.setmetatable or setmetatable
local copy
function copy(t)
if type(t)~="table" then
return t
elseif refs[t] then
return refs[t]
else
local c = {}
refs[t] = c
for k, v in next, t do
if rk then
k = copy(k)
end
if rv then
c[k] = copy(v)
else
c[k] = v
end
end
if mt == "reuse" then
setmetatable(c,getmetatable(t))
elseif mt == "copy" then
setmetatable(c,copy(getmetatable(t)))
end
return c
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment