diff options
-rw-r--r-- | runtime/doc/lua.txt | 16 | ||||
-rw-r--r-- | runtime/lua/vim/shared.lua | 27 | ||||
-rw-r--r-- | test/functional/lua/vim_spec.lua | 6 |
3 files changed, 49 insertions, 0 deletions
diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index bd821c4f9e..21f44ce02e 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -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. diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index 3eb332279a..f0dc34608c 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -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! diff --git a/test/functional/lua/vim_spec.lua b/test/functional/lua/vim_spec.lua index 38cb54fbc6..1547f3244e 100644 --- a/test/functional/lua/vim_spec.lua +++ b/test/functional/lua/vim_spec.lua @@ -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} |