Created
May 25, 2011 15:29
-
-
Save stuartpb/991174 to your computer and use it in GitHub Desktop.
Monstrous one-size-fits-all Lua table copy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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