Created
July 4, 2013 14:01
-
-
Save aidansmyth/5928043 to your computer and use it in GitHub Desktop.
Lua functions to copy a table not just reference the original table and it's data
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
-- From: lua-users.org | |
-- http://lua-users.org/wiki/CopyTable | |
--[[ | |
Shallow Copy | |
This a simple, naive implementation. It only copies the top level value and its direct children; there is no handling of deeper children, metatables or special types such as userdata or coroutines. It is also susceptible to influence by the __pairs metamethod. | |
]]-- | |
function shallowcopy(orig) | |
local orig_type = type(orig) | |
local copy | |
if orig_type == 'table' then | |
copy = {} | |
for orig_key, orig_value in pairs(orig) do | |
copy[orig_key] = orig_value | |
end | |
else -- number, string, boolean, etc | |
copy = orig | |
end | |
return copy | |
end | |
--[[ | |
Deep Copy | |
A deep copy copies all levels (or a specific subset of levels). | |
Here is a simple recursive implementation that additionally handles metatables and avoid the __pairs metamethod. | |
]]-- | |
function deepcopy(orig) | |
local orig_type = type(orig) | |
local copy | |
if orig_type == 'table' then | |
copy = {} | |
for orig_key, orig_value in next, orig, nil do | |
copy[deepcopy(orig_key)] = deepcopy(orig_value) | |
end | |
setmetatable(copy, deepcopy(getmetatable(orig))) | |
else -- number, string, boolean, etc | |
copy = orig | |
end | |
return copy | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment