Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- LotteryClass
- -- Used for choosing items based on weight
- -- Items Format:
- -- [index] = number weight
- -- Functions
- function shuffle(tbl)
- for i = #tbl, 2, -1 do
- local j = math.random(i)
- tbl[i], tbl[j] = tbl[j], tbl[i]
- end
- return tbl
- end
- -- Main
- local LotteryClass = {}
- LotteryClass.__index = LotteryClass
- function LotteryClass.new()
- local self = setmetatable({
- _items = {},
- _totalWeight = 0
- }, LotteryClass)
- return self
- end
- function LotteryClass:SetItems(items)
- self._items = items
- self._totalWeight = 0
- for item, weight in pairs(items) do
- self._totalWeight += weight
- items[item] = weight
- end
- end
- function LotteryClass:GetChance(index)
- local ItemWeight = self._items[index] or 0
- return ItemWeight / self._totalWeight
- end
- function LotteryClass:Spin()
- local Selection = {}
- for index, weight in pairs(self._items) do
- for i = 1, weight do
- table.insert(Selection, index)
- end
- end
- Selection = shuffle(Selection)
- -- Pick and return the result
- local Index = math.random(#Selection)
- local Result = Selection[Index]
- return Result, Selection, Index
- end
- return LotteryClass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement