F.lua 1.1 KB

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