neovim

Neovim text editor
git clone https://git.dasho.dev/neovim.git
Log | Files | Refs | README

F.lua (1175B)


      1 local F = {}
      2 
      3 --- Returns the first argument which is not nil.
      4 ---
      5 --- If all arguments are nil, returns nil.
      6 ---
      7 --- Examples:
      8 ---
      9 --- ```lua
     10 --- local a = nil
     11 --- local b = nil
     12 --- local c = 42
     13 --- local d = true
     14 --- assert(vim.F.if_nil(a, b, c, d) == 42)
     15 --- ```
     16 ---
     17 ---@generic T
     18 ---@param ... T
     19 ---@return T
     20 function F.if_nil(...)
     21  local nargs = select('#', ...)
     22  for i = 1, nargs do
     23    local v = select(i, ...)
     24    if v ~= nil then
     25      return v
     26    end
     27  end
     28  return nil
     29 end
     30 
     31 -- Use in combination with pcall
     32 function F.ok_or_nil(status, ...)
     33  if not status then
     34    return
     35  end
     36  return ...
     37 end
     38 
     39 -- Nil pcall.
     40 --- @generic T
     41 --- @param fn  fun(...):T
     42 --- @param ... T?
     43 --- @return T
     44 function F.npcall(fn, ...)
     45  return F.ok_or_nil(pcall(fn, ...))
     46 end
     47 
     48 --- Wrap a function to return nil if it fails, otherwise the value
     49 function F.nil_wrap(fn)
     50  return function(...)
     51    return F.npcall(fn, ...)
     52  end
     53 end
     54 
     55 --- like {...} except preserve the length explicitly
     56 function F.pack_len(...)
     57  return { n = select('#', ...), ... }
     58 end
     59 
     60 --- like unpack() but use the length set by F.pack_len if present
     61 function F.unpack_len(t)
     62  return unpack(t, 1, t.n)
     63 end
     64 
     65 return F