Skip to content

Instantly share code, notes, and snippets.

@datatypevoid
Forked from MihailJP/d_copy.lua
Created March 23, 2017 15:09
Show Gist options
  • Select an option

  • Save datatypevoid/19310169d4e78813e6224aba1f0af549 to your computer and use it in GitHub Desktop.

Select an option

Save datatypevoid/19310169d4e78813e6224aba1f0af549 to your computer and use it in GitHub Desktop.
Shallow- and deep-copy of table in Lua
function clone (t) -- deep-copy a table
if type(t) ~= "table" then return t end
local meta = getmetatable(t)
local target = {}
for k, v in pairs(t) do
if type(v) == "table" then
target[k] = clone(v)
else
target[k] = v
end
end
setmetatable(target, meta)
return target
end
function copy (t) -- shallow-copy a table
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)
return target
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment