Skip to content

Instantly share code, notes, and snippets.

@aidansmyth
Created July 4, 2013 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aidansmyth/5928043 to your computer and use it in GitHub Desktop.
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
-- 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