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
41
table.lua
41
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,13 +380,15 @@ 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
|
||||||
if copies[value] then
|
return value
|
||||||
return copies[value]
|
|
||||||
end
|
|
||||||
return _deepcopy(value)
|
|
||||||
end
|
end
|
||||||
return value
|
|
||||||
|
if copies[value] then
|
||||||
|
return copies[value]
|
||||||
|
end
|
||||||
|
|
||||||
|
return _deepcopy(value)
|
||||||
end
|
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)
|
||||||
@ -495,7 +516,7 @@ end
|
|||||||
function process(tab, func)
|
function process(tab, func)
|
||||||
local results = {}
|
local results = {}
|
||||||
for key, value in pairs(tab) do
|
for key, value in pairs(tab) do
|
||||||
table.insert(results, func(key,value))
|
table.insert(results, func(key, value))
|
||||||
end
|
end
|
||||||
return results
|
return results
|
||||||
end
|
end
|
||||||
|
Loading…
Reference in New Issue
Block a user