aboutsummaryrefslogtreecommitdiff
path: root/runtime/lua/vim/F.lua
blob: 5ed60ca8ab2faa285a72d1faa43928727bd0f82a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
local F = {}

--- Returns the first argument which is not nil.
---
--- If all arguments are nil, returns nil.
---
--- Examples:
---
--- ```lua
--- local a = nil
--- local b = nil
--- local c = 42
--- local d = true
--- assert(vim.F.if_nil(a, b, c, d) == 42)
--- ```
---
---@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