hexyz is tower defense game, and a lua library for dealing with hexagonal grids
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
2.5 KiB

3 years ago
  1. -- utility functions that don't below elsewhere go here,
  2. -- especially if they would be at home on the global 'math' or 'table' variables, or are otherwise extensions of standard lua features
  3. -- try to avoid *too* much amulet specific stuff, but vector types are probably ok.
  4. function fprofile(f, ...)
  5. local t1 = am.current_time()
  6. local result = { f(...) }
  7. local time = am.current_time() - t1
  8. --log("%f", time)
  9. return time, unpack(result)
  10. end
  11. function math.wrapf(float, range)
  12. return float - range * math.floor(float / range)
  13. end
  14. function math.lerp(v1, v2, t)
  15. return v1 * t + v2 * (1 - t)
  16. end
  17. -- manually found the smallest number, doesn't make sense to me why, but hey it's one less than a power of two which is probably significant
  18. -- pretty sure IEEE-754's smallest value is less than this, 32bit or 64bit
  19. math.SMALLEST_NUMBER_ABOVE_0 = 2 ^ (-1023)
  20. -- don't use this with sparse arrays
  21. function table.rchoice(t)
  22. return t[math.floor(math.random() * #t) + 1]
  23. end
  24. function table.count(t)
  25. local count = 0
  26. for i,v in pairs(t) do
  27. if v ~= nil then
  28. count = count + 1
  29. end
  30. end
  31. return count
  32. end
  33. function table.highest_index(t)
  34. local highest = nil
  35. for i,v in pairs(t) do
  36. if i and not highest then
  37. highest = i
  38. end
  39. if i > highest then
  40. highest = i
  41. end
  42. end
  43. return highest
  44. end
  45. function table.find(t, predicate)
  46. for i,v in pairs(t) do
  47. if predicate(v) then
  48. return i,v
  49. end
  50. end
  51. return nil
  52. end
  53. -- don't use with sparse arrays or hash tables.
  54. -- only arrays.
  55. -- mutates the array in place.
  56. function table.reverse(t)
  57. local n = #t
  58. for i,v in pairs(t) do
  59. t[i], t[n] = t[n], t[i]
  60. n = n - 1
  61. end
  62. end
  63. function table.quicksort(t, low_index, high_index, comparator)
  64. local function partition(t, low_index, high_index)
  65. local i = low_index - 1
  66. local pivot = t[high_index]
  67. for j = low_index, high_index - 1 do
  68. if comparator(t[j], t[pivot]) <= 0 then
  69. i = i + 1
  70. t[i], t[j] = t[j], t[i]
  71. end
  72. end
  73. t[i + 1], t[high_index] = t[high_index], t[i + 1]
  74. return i + 1
  75. end
  76. if #t == 1 then
  77. return t
  78. end
  79. if comparator(t[low_index], t[high_index]) < 0 then
  80. local partition_index = partition(t, low_index, high_index)
  81. quicksort(t, low_index, partition_index - 1, comparator)
  82. quicksort(t, partition_index + 1, high_index, comparator)
  83. end
  84. return t
  85. end