mirror of
https://github.com/appgurueu/modlib.git
synced 2024-11-26 01:03:46 +01:00
Make all table copy variants preserve metatables
This commit is contained in:
parent
0d864f0065
commit
aca117a244
33
table.lua
33
table.lua
@ -327,17 +327,36 @@ function same(a, b)
|
|||||||
return is_same(a, b)
|
return is_same(a, b)
|
||||||
end
|
end
|
||||||
|
|
||||||
function shallowcopy(table)
|
function shallowcopy(
|
||||||
|
table -- table to copy
|
||||||
|
, strip_metatables -- whether to strip metatables; falsy by default; metatables are not copied
|
||||||
|
)
|
||||||
|
if type(table) ~= "table" then
|
||||||
|
return table
|
||||||
|
end
|
||||||
|
|
||||||
local copy = {}
|
local copy = {}
|
||||||
|
if not strip_metatables then
|
||||||
|
setmetatable(copy, getmetatable(table))
|
||||||
|
end
|
||||||
for key, value in pairs(table) do
|
for key, value in pairs(table) do
|
||||||
copy[key] = value
|
copy[key] = value
|
||||||
end
|
end
|
||||||
return copy
|
return copy
|
||||||
end
|
end
|
||||||
|
|
||||||
function deepcopy_tree(table)
|
function deepcopy_tree(
|
||||||
if type(table) ~= "table" then return table end
|
table -- table; may not contain circular references; cross references will be copied multiple times
|
||||||
|
, strip_metatables -- whether to strip metatables; falsy by default; metatables are not copied
|
||||||
|
)
|
||||||
|
if type(table) ~= "table" then
|
||||||
|
return table
|
||||||
|
end
|
||||||
|
|
||||||
local copy = {}
|
local copy = {}
|
||||||
|
if not strip_metatables then
|
||||||
|
setmetatable(copy, getmetatable(table))
|
||||||
|
end
|
||||||
for key, value in pairs(table) do
|
for key, value in pairs(table) do
|
||||||
copy[deepcopy_tree(key)] = deepcopy_tree(value)
|
copy[deepcopy_tree(key)] = deepcopy_tree(value)
|
||||||
end
|
end
|
||||||
@ -361,14 +380,16 @@ function deepcopy(
|
|||||||
end
|
end
|
||||||
copies[table] = copy
|
copies[table] = copy
|
||||||
local function _copy(value)
|
local function _copy(value)
|
||||||
if type(value) == "table" then
|
if type(value) ~= "table" then
|
||||||
|
return value
|
||||||
|
end
|
||||||
|
|
||||||
if copies[value] then
|
if copies[value] then
|
||||||
return copies[value]
|
return copies[value]
|
||||||
end
|
end
|
||||||
|
|
||||||
return _deepcopy(value)
|
return _deepcopy(value)
|
||||||
end
|
end
|
||||||
return value
|
|
||||||
end
|
|
||||||
for key, value in pairs(table) do
|
for key, value in pairs(table) do
|
||||||
copy[_copy(key)] = _copy(value)
|
copy[_copy(key)] = _copy(value)
|
||||||
end
|
end
|
||||||
|
Loading…
Reference in New Issue
Block a user