소스 검색

Added randomizer utility module

Nathan Schneider 2 년 전
부모
커밋
fa50a59938
2개의 변경된 파일51개의 추가작업 그리고 0개의 파일을 삭제
  1. 1 0
      modpol_core/api.lua
  2. 50 0
      modpol_core/modules/randomizer.lua

+ 1 - 0
modpol_core/api.lua

@@ -18,6 +18,7 @@ dofile (localdir .. "/modules/consent.lua")
 dofile (localdir .. "/modules/join_org_consent.lua")
 dofile (localdir .. "/modules/leave_org.lua")
 dofile (localdir .. "/modules/message_org.lua")
+dofile (localdir .. "/modules/random.lua")
 dofile (localdir .. "/modules/remove_child_consent.lua")
 dofile (localdir .. "/modules/remove_member_consent.lua")
 dofile (localdir .. "/modules/remove_org_consent.lua")

+ 50 - 0
modpol_core/modules/randomizer.lua

@@ -0,0 +1,50 @@
+--- @module randomizer
+-- A utility module that outputs a random result from a set of options
+
+local randomizer = {
+    name = "Randomizer",
+    slug = "randomizer",
+    desc = "A utility module other modules use for random decisions",
+    hide = true
+}
+
+randomizer.data = {
+}
+
+-- options_table should be a table of strings
+randomizer.config = {
+    options_table = {},
+    num_results = 1,
+    result_table = {}
+}
+
+function randomizer:initiate(result)
+   self.data.result = result
+   self.data.options_table = modpol.util.copy_table(self.config.options_table)
+   -- if options table is empty, randomizer returns that
+   if #self.data.options_table == 0 or self.config.num_results == 0 then
+      if self.data.result then
+         self.data.result({}) end
+      self.org:wipe_pending_actions(self.id)
+      self.org:delete_process(self.id)
+   else
+      -- otherwise, choose a random result
+      self.random_loop()
+   end
+end
+
+-- returns result_table
+function randomizer:random_loop()
+   self.data.results = 0
+   if results == self.config.num_results then
+      self.data.result(self.data.result_table)
+   else
+      math.randomseed(os.time())
+      local index = math.random(self.data.options_table)
+      table.insert(self.data.result_table, self.data.options_table[index])
+      table.remove(self.data.options_table, index)
+      self.data.results = self.data.results + 1
+   end
+end
+   
+modpol.modules.randomizer = randomizer