Amend the copying functions

This commit is contained in:
Ishaan Bhardwaj 2021-08-27 17:18:06 -04:00
parent 6cf6568a57
commit 0e1f40ad30

View File

@ -1,10 +1,20 @@
function copy(t)
-- returns deep copy of t (as opposed to the shallow copy you get from var = t)
-- returns top-layer shallow copy of t
if type(t) ~= "table" then return t end
local meta = getmetatable(t)
local target = {}
for k, v in pairs(t) do target[k] = v end
setmetatable(target, meta)
for k, v in next, t do target[k] = v end
setmetatable(target, getmetatable(t))
return target
end
function deepcopy(t)
-- returns infinite-layer deep copy of t
if type(t) ~= "table" then return t end
local target = {}
for k, v in next, t do
target[deepcopy(k)] = deepcopy(v)
end
setmetatable(target, deepcopy(getmetatable(t)))
return target
end