support cpying self-referenced table (#2076)

This commit is contained in:
hrsh7th
2024-11-02 13:54:35 +09:00
committed by GitHub
parent 7d4051064c
commit f17d9b4394
2 changed files with 53 additions and 15 deletions

View File

@@ -156,28 +156,39 @@ misc.set = function(t, keys, v)
c[keys[#keys]] = v
end
---Copy table
---@generic T
---@param tbl T
---@return T
misc.copy = function(tbl)
if type(tbl) ~= 'table' then
return tbl
end
do
local function do_copy(tbl, seen)
if type(tbl) ~= 'table' then
return tbl
end
if seen[tbl] then
return seen[tbl]
end
if islist(tbl) then
local copy = {}
seen[tbl] = copy
for i, value in ipairs(tbl) do
copy[i] = do_copy(value, seen)
end
return copy
end
if islist(tbl) then
local copy = {}
for i, value in ipairs(tbl) do
copy[i] = misc.copy(value)
seen[tbl] = copy
for key, value in pairs(tbl) do
copy[key] = do_copy(value, seen)
end
return copy
end
local copy = {}
for key, value in pairs(tbl) do
copy[key] = misc.copy(value)
---Copy table
---@generic T
---@param tbl T
---@return T
misc.copy = function(tbl)
return do_copy(tbl, {})
end
return copy
end
---Safe version of vim.str_utfindex