Skip to content

Instantly share code, notes, and snippets.

@MihailJP
Created October 22, 2012 14:47
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save MihailJP/3931841 to your computer and use it in GitHub Desktop.
Save MihailJP/3931841 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