aboutsummaryrefslogtreecommitdiff
path: root/runtime/lua/vim/shared.lua
diff options
context:
space:
mode:
authorMichael Lingelbach <m.j.lbach@gmail.com>2022-03-24 12:01:04 -0700
committerGitHub <noreply@github.com>2022-03-24 12:01:04 -0700
commit69f1de86dca28d6e339351082df1309ef4fbb6a6 (patch)
treec65bd5aed8ab2d64a42b7dabc7180af0ad0fd68e /runtime/lua/vim/shared.lua
parent39af40580a1788b4569c66aa710330f50707e976 (diff)
downloadrneovim-69f1de86dca28d6e339351082df1309ef4fbb6a6.tar.gz
rneovim-69f1de86dca28d6e339351082df1309ef4fbb6a6.tar.bz2
rneovim-69f1de86dca28d6e339351082df1309ef4fbb6a6.zip
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.
Diffstat (limited to 'runtime/lua/vim/shared.lua')
-rw-r--r--runtime/lua/vim/shared.lua27
1 files changed, 27 insertions, 0 deletions
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!