2
0

randomizer.lua 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. --- A utility module that outputs a random result from a set of options
  2. -- @module randomizer
  3. local randomizer = {
  4. name = "Randomizer",
  5. slug = "randomizer",
  6. desc = "A utility module other modules use for random decisions",
  7. hide = true
  8. }
  9. randomizer.data = {
  10. }
  11. -- options_table should be a table of strings
  12. randomizer.config = {
  13. options_table = {},
  14. num_results = 1,
  15. result_table = {}
  16. }
  17. --- Initiate function
  18. -- @function randomizer:initiate
  19. -- @param result Callback if this module is embedded in other modules
  20. function randomizer:initiate(result)
  21. self.data.result = result
  22. self.data.options_table = modpol.util.copy_table(self.config.options_table)
  23. -- if options table is empty, randomizer returns that
  24. if #self.data.options_table == 0 or self.config.num_results == 0 then
  25. if self.data.result then
  26. self.data.result({}) end
  27. self.org:delete_process(self.id)
  28. else
  29. -- otherwise, choose a random result
  30. self.random_loop()
  31. end
  32. end
  33. --- Returns result_table
  34. -- @function randomizer:random_loop
  35. function randomizer:random_loop()
  36. self.data.results = 0
  37. if results == self.config.num_results then
  38. self.data.result(self.data.result_table)
  39. else
  40. math.randomseed(os.time())
  41. local index = math.random(self.data.options_table)
  42. table.insert(self.data.result_table, self.data.options_table[index])
  43. table.remove(self.data.options_table, index)
  44. self.data.results = self.data.results + 1
  45. end
  46. end
  47. modpol.modules.randomizer = randomizer