F.lua 791 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. local F = {}
  2. --- Returns {a} if it is not nil, otherwise returns {b}.
  3. ---
  4. ---@param a
  5. ---@param b
  6. function F.if_nil(a, b)
  7. if a == nil then
  8. return b
  9. end
  10. return a
  11. end
  12. -- Use in combination with pcall
  13. function F.ok_or_nil(status, ...)
  14. if not status then
  15. return
  16. end
  17. return ...
  18. end
  19. -- Nil pcall.
  20. function F.npcall(fn, ...)
  21. return F.ok_or_nil(pcall(fn, ...))
  22. end
  23. --- Wrap a function to return nil if it fails, otherwise the value
  24. function F.nil_wrap(fn)
  25. return function(...)
  26. return F.npcall(fn, ...)
  27. end
  28. end
  29. --- like {...} except preserve the length explicitly
  30. function F.pack_len(...)
  31. return { n = select('#', ...), ... }
  32. end
  33. --- like unpack() but use the length set by F.pack_len if present
  34. function F.unpack_len(t)
  35. return unpack(t, 1, t.n)
  36. end
  37. return F