util.lua 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. ----------------
  2. -- Class
  3. ----------------
  4. function new(x, ...)
  5. local t = extend(x)
  6. if t.init then
  7. t:init(...)
  8. end
  9. return t
  10. end
  11. function extend(x)
  12. local t = {}
  13. setmetatable(t, {__index = x, __call = new})
  14. return t
  15. end
  16. function class() return extend() end
  17. ----------------
  18. -- Math
  19. ----------------
  20. function math.sign(x) return x > 0 and 1 or x < 0 and -1 or 0 end
  21. function math.round(x) return math.sign(x) >= 0 and math.floor(x + .5) or math.ceil(x - .5) end
  22. function math.clamp(x, l, h) return math.min(math.max(x, l), h) end
  23. function math.lerp(x1, x2, z) return x1 + (x2 - x1) * z end
  24. function math.anglerp(d1, d2, z) return d1 + (math.anglediff(d1, d2) * z) end
  25. function math.dx(len, dir) return len * math.cos(dir) end
  26. function math.dy(len, dir) return len * math.sin(dir) end
  27. function math.distance(x1, y1, x2, y2) return ((x2 - x1) ^ 2 + (y2 - y1) ^ 2) ^ .5 end
  28. function math.direction(x1, y1, x2, y2) return math.atan2(y2 - y1, x2 - x1) end
  29. function math.vector(...) return math.distance(...), math.direction(...) end
  30. function math.inside(px, py, rx, ry, rw, rh) return px >= rx and px <= rx + rw and py >= ry and py <= ry + rh end
  31. function math.anglediff(d1, d2) return math.rad((((math.deg(d2) - math.deg(d1) % 360) + 540) % 360) - 180) end
  32. ----------------
  33. -- Table
  34. ----------------
  35. function table.copy(x)
  36. local t = type(x)
  37. if t ~= 'table' then return x end
  38. local y = {}
  39. for k, v in next, x, nil do y[k] = table.copy(v) end
  40. setmetatable(y, getmetatable(x))
  41. return y
  42. end
  43. function table.has(t, x)
  44. local f = deep and rawequal
  45. for _, v in pairs(t) do if f(v, x) then return true end end
  46. return false
  47. end
  48. function table.each(t, f)
  49. if not t then return end
  50. for k, v in pairs(t) do if f(v, k) then break end end
  51. end
  52. function table.with(t, k, ...)
  53. return table.each(t, f.egoexe(k, ...))
  54. end
  55. ----------------
  56. -- Functions
  57. ----------------
  58. f = {}
  59. f.egoexe = function(f, ...) local a = {...} return function(x) if x[f] then x[f](x, unpack(a)) end end end