mirror of
https://github.com/neovim/neovim.git
synced 2026-04-20 06:20:53 +00:00
lua: allow deepcopy of functions (#12136)
This commit is contained in:
@@ -908,7 +908,10 @@ deep_equal({a}, {b}) *vim.deep_equal()*
|
||||
deepcopy({orig}) *vim.deepcopy()*
|
||||
Returns a deep copy of the given object. Non-table objects are
|
||||
copied as in a typical Lua assignment, whereas table objects
|
||||
are copied recursively.
|
||||
are copied recursively. Functions are naively copied, so
|
||||
functions in the copied table point to the same functions as
|
||||
those in the input table. Userdata and threads are not copied
|
||||
and will throw an error.
|
||||
|
||||
Parameters: ~
|
||||
{orig} Table to copy
|
||||
|
||||
@@ -8,6 +8,9 @@ local vim = vim or {}
|
||||
|
||||
--- Returns a deep copy of the given object. Non-table objects are copied as
|
||||
--- in a typical Lua assignment, whereas table objects are copied recursively.
|
||||
--- Functions are naively copied, so functions in the copied table point to the
|
||||
--- same functions as those in the input table. Userdata and threads are not
|
||||
--- copied and will throw an error.
|
||||
---
|
||||
--@param orig Table to copy
|
||||
--@returns New table of copied keys and (nested) values.
|
||||
@@ -34,10 +37,16 @@ vim.deepcopy = (function()
|
||||
string = _id,
|
||||
['nil'] = _id,
|
||||
boolean = _id,
|
||||
['function'] = _id,
|
||||
}
|
||||
|
||||
return function(orig)
|
||||
return deepcopy_funcs[type(orig)](orig)
|
||||
local f = deepcopy_funcs[type(orig)]
|
||||
if f then
|
||||
return f(orig)
|
||||
else
|
||||
error("Cannot deepcopy object of type "..type(orig))
|
||||
end
|
||||
end
|
||||
end)()
|
||||
|
||||
|
||||
@@ -341,6 +341,22 @@ describe('lua stdlib', function()
|
||||
and vim.tbl_count(b) == 2
|
||||
and tostring(a) ~= tostring(b)
|
||||
]]))
|
||||
|
||||
ok(exec_lua([[
|
||||
local f1 = function() return 1 end
|
||||
local f2 = function() return 2 end
|
||||
local t1 = {f = f1}
|
||||
local t2 = vim.deepcopy(t1)
|
||||
t1.f = f2
|
||||
return t1.f() ~= t2.f()
|
||||
]]))
|
||||
|
||||
eq('Error executing lua: .../shared.lua: Cannot deepcopy object of type thread',
|
||||
pcall_err(exec_lua, [[
|
||||
local thread = coroutine.create(function () return 0 end)
|
||||
local t = {thr = thread}
|
||||
vim.deepcopy(t)
|
||||
]]))
|
||||
end)
|
||||
|
||||
it('vim.pesc', function()
|
||||
|
||||
Reference in New Issue
Block a user