mirror of
https://github.com/neovim/neovim
synced 2025-07-16 01:01:49 +00:00
feat(lua): allow vim.F.if_nil to take multiple arguments (#22903)
The first argument which is non-nil is returned. This is useful when using nested default values (e.g. in the EditorConfig plugin). Before: local enable = vim.F.if_nil(vim.b.editorconfig, vim.F.if_nil(vim.g.editorconfig, true)) After: local enable = vim.F.if_nil(vim.b.editorconfig, vim.g.editorconfig, true)
This commit is contained in:
@ -1,18 +1,29 @@
|
||||
local F = {}
|
||||
|
||||
--- Returns {a} if it is not nil, otherwise returns {b}.
|
||||
--- Returns the first argument which is not nil.
|
||||
---
|
||||
---@generic A
|
||||
---@generic B
|
||||
--- If all arguments are nil, returns nil.
|
||||
---
|
||||
---@param a A
|
||||
---@param b B
|
||||
---@return A | B
|
||||
function F.if_nil(a, b)
|
||||
if a == nil then
|
||||
return b
|
||||
--- Examples:
|
||||
--- <pre>
|
||||
--- local a = nil
|
||||
--- local b = nil
|
||||
--- local c = 42
|
||||
--- local d = true
|
||||
--- assert(vim.F.if_nil(a, b, c, d) == 42)
|
||||
--- </pre>
|
||||
---
|
||||
---@param ... any
|
||||
---@return any
|
||||
function F.if_nil(...)
|
||||
local nargs = select('#', ...)
|
||||
for i = 1, nargs do
|
||||
local v = select(i, ...)
|
||||
if v ~= nil then
|
||||
return v
|
||||
end
|
||||
end
|
||||
return a
|
||||
return nil
|
||||
end
|
||||
|
||||
-- Use in combination with pcall
|
||||
|
Reference in New Issue
Block a user