LotteryClass | Chance systems simplified

I made a module a few weeks ago for picking things based on chance, this is useful instead of having to rewrite selection tables and whatnot.

You can find the code here:

Or you can find the download here:
https://www.roblox.com/library/6955485409/Lottery

FYI there is another module which accomplishes the same task in a different method and is more optimized you can find it here :slightly_smiling_face:


Functions
GetChance(index) returns the chance for index to be chosen as a number from 0-1. returns 0 if index is not in table

Spin() returns a random item, the selection table used, and the index of the result

SetItems() used for setting the item table, format = [<any> index] = <number> weight


Example

Egg System

local Lottery = require(path.to.Lottery)

-- Crate lotto and pick
local Egg = {
    ["Dumb"] = 2,
    ["Idiot"] = 5,
    ["Example"] = 2,
    ["Words"] = 1
}

local PetLotto = Lottery.new()
PetLotto:SetItems(Egg)

local ChosenPet = PetLotto:Spin()
print(ChosenPet, PetLotto:GetChance(ChosenPet))
11 Likes

4 Likes

See it’s nice from a glance but the Spin function scares me. Particularly what scares me about it is the efficiency of your method: it isn’t doing actual weighting and instead is using the weight number to repeatedly insert items into a table.

Items with a higher weight means significantly large tables. Additionally since you don’t use table.create with the “weight” passed as the size, the item table will reallocate every iteration of the for loop. Not very friendly on performance, excluding the fact that there’s shuffling done afterward.

You might want to take a look at the math behind LootPlan, another similar such module that involves actual weighting. In this case the module does not create new tables to generate loot to pick from but instead performs a bit of math across loot chances added to a plan in terms of percentages.

1 Like

I did consider optimizing it, but due to the fact I wasn’t going to be calling Spin 10-30 times within the same second, I didn’t bother. There is nothing stopping anyone from optimizing it themselves though, its not a long script and is clean I think and easy to understand.

I’m just open-sourcing this for other people who might randomly stumble upon needing this I will add that module to the original post though.

1 Like