F.lua 775 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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 return b end
  8. return a
  9. end
  10. -- Use in combination with pcall
  11. function F.ok_or_nil(status, ...)
  12. if not status then return end
  13. return ...
  14. end
  15. -- Nil pcall.
  16. function F.npcall(fn, ...)
  17. return F.ok_or_nil(pcall(fn, ...))
  18. end
  19. --- Wrap a function to return nil if it fails, otherwise the value
  20. function F.nil_wrap(fn)
  21. return function(...)
  22. return F.npcall(fn, ...)
  23. end
  24. end
  25. --- like {...} except preserve the length explicitly
  26. function F.pack_len(...)
  27. return {n=select('#', ...), ...}
  28. end
  29. --- like unpack() but use the length set by F.pack_len if present
  30. function F.unpack_len(t)
  31. return unpack(t, 1, t.n)
  32. end
  33. return F