Created
October 22, 2012 14:47
-
-
Save MihailJP/3931841 to your computer and use it in GitHub Desktop.
Shallow- and deep-copy of table in Lua
This file contains hidden or 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
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 |
This file contains hidden or 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
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