mirror of
https://github.com/neovim/neovim.git
synced 2024-12-20 11:15:14 -07:00
d675bd01b1
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)
60 lines
1.1 KiB
Lua
60 lines
1.1 KiB
Lua
local F = {}
|
|
|
|
--- Returns the first argument which is not nil.
|
|
---
|
|
--- If all arguments are nil, returns nil.
|
|
---
|
|
--- 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 nil
|
|
end
|
|
|
|
-- Use in combination with pcall
|
|
function F.ok_or_nil(status, ...)
|
|
if not status then
|
|
return
|
|
end
|
|
return ...
|
|
end
|
|
|
|
-- Nil pcall.
|
|
function F.npcall(fn, ...)
|
|
return F.ok_or_nil(pcall(fn, ...))
|
|
end
|
|
|
|
--- Wrap a function to return nil if it fails, otherwise the value
|
|
function F.nil_wrap(fn)
|
|
return function(...)
|
|
return F.npcall(fn, ...)
|
|
end
|
|
end
|
|
|
|
--- like {...} except preserve the length explicitly
|
|
function F.pack_len(...)
|
|
return { n = select('#', ...), ... }
|
|
end
|
|
|
|
--- like unpack() but use the length set by F.pack_len if present
|
|
function F.unpack_len(t)
|
|
return unpack(t, 1, t.n)
|
|
end
|
|
|
|
return F
|