mirror of
https://github.com/neovim/neovim.git
synced 2025-09-05 19:08:15 +00:00
feat: allow function passed to defaulttable to take an argument (#22839)
Pass the value of the key being accessed to the create function, to allow users to dynamically generate default values.
This commit is contained in:
@@ -1635,8 +1635,8 @@ defaulttable({create}) *vim.defaulttable()*
|
||||
<
|
||||
|
||||
Parameters: ~
|
||||
• {create} (function|nil) The function called to create a missing
|
||||
value.
|
||||
• {create} function?(key:any):any The function called to create a
|
||||
missing value.
|
||||
|
||||
Return: ~
|
||||
(table) Empty table with metamethod
|
||||
|
@@ -796,13 +796,15 @@ end
|
||||
--- a.b.c = 1
|
||||
--- </pre>
|
||||
---
|
||||
---@param create function|nil The function called to create a missing value.
|
||||
---@param create function?(key:any):any The function called to create a missing value.
|
||||
---@return table Empty table with metamethod
|
||||
function vim.defaulttable(create)
|
||||
create = create or vim.defaulttable
|
||||
create = create or function(_)
|
||||
return vim.defaulttable()
|
||||
end
|
||||
return setmetatable({}, {
|
||||
__index = function(tbl, key)
|
||||
rawset(tbl, key, create())
|
||||
rawset(tbl, key, create(key))
|
||||
return rawget(tbl, key)
|
||||
end,
|
||||
})
|
||||
|
@@ -2915,6 +2915,15 @@ describe('lua stdlib', function()
|
||||
return a
|
||||
]])
|
||||
end)
|
||||
|
||||
it('accepts the key name', function()
|
||||
eq({ b = 'b', c = 'c' }, exec_lua [[
|
||||
local a = vim.defaulttable(function(k) return k end)
|
||||
local _ = a.b
|
||||
local _ = a.c
|
||||
return a
|
||||
]])
|
||||
end)
|
||||
end)
|
||||
|
||||
it('vim.lua_omnifunc', function()
|
||||
|
Reference in New Issue
Block a user