mirror of
https://github.com/neovim/neovim.git
synced 2025-09-06 03:18:16 +00:00
feat: add vim.tbl_get (#17831)
vim.tbl_get takes a table with subsequent string arguments (variadic) that index into the table. If the value pointed to by the set of keys exists, the function returns the value. If the set of keys does not exist, the function returns nil.
This commit is contained in:

committed by
GitHub

parent
39af40580a
commit
69f1de86dc
@@ -1634,6 +1634,22 @@ tbl_flatten({t}) *vim.tbl_flatten()*
|
||||
See also: ~
|
||||
From https://github.com/premake/premake-core/blob/master/src/base/table.lua
|
||||
|
||||
tbl_get({o}, {...}) *vim.tbl_get()*
|
||||
Index into a table (first argument) via string keys passed as
|
||||
subsequent arguments. Return `nil` if the key does not exist. Examples: >
|
||||
|
||||
vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
|
||||
vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
|
||||
<
|
||||
|
||||
Parameters: ~
|
||||
{o} Table to index
|
||||
{...} Optional strings (0 or more, variadic) via which to
|
||||
index the table
|
||||
|
||||
Return: ~
|
||||
nested value indexed by key if it exists, else nil
|
||||
|
||||
tbl_isempty({t}) *vim.tbl_isempty()*
|
||||
Checks if a table is empty.
|
||||
|
||||
|
@@ -347,6 +347,33 @@ function vim.tbl_add_reverse_lookup(o)
|
||||
return o
|
||||
end
|
||||
|
||||
--- Index into a table (first argument) via string keys passed as subsequent arguments.
|
||||
--- Return `nil` if the key does not exist.
|
||||
--_
|
||||
--- Examples:
|
||||
--- <pre>
|
||||
--- vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
|
||||
--- vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
|
||||
--- </pre>
|
||||
---
|
||||
---@param o Table to index
|
||||
---@param ... Optional strings (0 or more, variadic) via which to index the table
|
||||
---
|
||||
---@returns nested value indexed by key if it exists, else nil
|
||||
function vim.tbl_get(o, ...)
|
||||
local keys = {...}
|
||||
if #keys == 0 then
|
||||
return
|
||||
end
|
||||
for _, k in ipairs(keys) do
|
||||
o = o[k]
|
||||
if o == nil then
|
||||
return
|
||||
end
|
||||
end
|
||||
return o
|
||||
end
|
||||
|
||||
--- Extends a list-like table with the values of another list-like table.
|
||||
---
|
||||
--- NOTE: This mutates dst!
|
||||
|
@@ -490,6 +490,12 @@ describe('lua stdlib', function()
|
||||
eq(false, exec_lua("return vim.tbl_isempty({a=1, b=2, c=3})"))
|
||||
end)
|
||||
|
||||
it('vim.tbl_get', function()
|
||||
eq(true, exec_lua("return vim.tbl_get({ test = { nested_test = true }}, 'test', 'nested_test')"))
|
||||
eq(NIL, exec_lua("return vim.tbl_get({}, 'missing_key')"))
|
||||
eq(NIL, exec_lua("return vim.tbl_get({})"))
|
||||
end)
|
||||
|
||||
it('vim.tbl_extend', function()
|
||||
ok(exec_lua([[
|
||||
local a = {x = 1}
|
||||
|
Reference in New Issue
Block a user