Advertisement
BossSpaz

Lottery Class

Jun 6th, 2021 (edited)
538
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.16 KB | None | 0 0
  1. -- LotteryClass
  2. -- Used for choosing items based on weight
  3.  
  4. -- Items Format:
  5. -- [index] = number weight
  6.  
  7. -- Functions
  8. function shuffle(tbl)
  9.     for i = #tbl, 2, -1 do
  10.         local j = math.random(i)
  11.         tbl[i], tbl[j] = tbl[j], tbl[i]
  12.     end
  13.     return tbl
  14. end
  15.  
  16. -- Main
  17. local LotteryClass = {}
  18. LotteryClass.__index = LotteryClass
  19.  
  20. function LotteryClass.new()
  21.     local self = setmetatable({
  22.         _items = {},
  23.         _totalWeight = 0
  24.     }, LotteryClass)   
  25.     return self
  26. end
  27.  
  28. function LotteryClass:SetItems(items)
  29.     self._items = items
  30.     self._totalWeight = 0
  31.     for item, weight in pairs(items) do
  32.         self._totalWeight += weight
  33.         items[item] = weight
  34.     end
  35. end
  36.  
  37. function LotteryClass:GetChance(index)
  38.     local ItemWeight = self._items[index] or 0
  39.     return ItemWeight / self._totalWeight
  40. end
  41.  
  42. function LotteryClass:Spin()
  43.     local Selection = {}
  44.     for index, weight in pairs(self._items) do
  45.         for i = 1, weight do
  46.             table.insert(Selection, index)
  47.         end
  48.     end
  49.    
  50.     Selection = shuffle(Selection)
  51.    
  52.     -- Pick and return the result
  53.     local Index = math.random(#Selection)
  54.     local Result = Selection[Index]
  55.     return Result, Selection, Index
  56. end
  57.  
  58. return LotteryClass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement