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.

100 lines
2.3 KiB

  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. -- don't use this with sparse arrays
  18. function table.rchoice(t)
  19. return t[math.floor(math.random() * #t) + 1]
  20. end
  21. function table.count(t)
  22. local count = 0
  23. for i,v in pairs(t) do
  24. if v ~= nil then
  25. count = count + 1
  26. end
  27. end
  28. return count
  29. end
  30. function table.highest_index(t)
  31. local highest = nil
  32. for i,v in pairs(t) do
  33. if i and not highest then
  34. highest = i
  35. end
  36. if i > highest then
  37. highest = i
  38. end
  39. end
  40. return highest
  41. end
  42. function table.find(t, predicate)
  43. for i,v in pairs(t) do
  44. if predicate(v) then
  45. return i,v
  46. end
  47. end
  48. return nil
  49. end
  50. -- don't use with sparse arrays or hash tables.
  51. -- only arrays.
  52. -- mutates the array in place.
  53. function table.reverse(t)
  54. local n = #t
  55. for i,v in pairs(t) do
  56. t[i], t[n] = t[n], t[i]
  57. n = n - 1
  58. end
  59. end
  60. function table.quicksort(t, low_index, high_index, comparator)
  61. local function partition(t, low_index, high_index)
  62. local i = low_index - 1
  63. local pivot = t[high_index]
  64. for j = low_index, high_index - 1 do
  65. if comparator(t[j], t[pivot]) <= 0 then
  66. i = i + 1
  67. t[i], t[j] = t[j], t[i]
  68. end
  69. end
  70. t[i + 1], t[high_index] = t[high_index], t[i + 1]
  71. return i + 1
  72. end
  73. if #t == 1 then
  74. return t
  75. end
  76. if comparator(t[low_index], t[high_index]) < 0 then
  77. local partition_index = partition(t, low_index, high_index)
  78. quicksort(t, low_index, partition_index - 1, comparator)
  79. quicksort(t, partition_index + 1, high_index, comparator)
  80. end
  81. return t
  82. end