How to make a system where I can store Rarities with chances?

I want to make a completely RNG based game, where a player can roll rarities. A person clicks on a GUI, the random function starts, the player will see which rarity he gets (ex. Basic 1.42 (like 1/1.42)), he clicks again and rolls Legendary 412.43 (1/412.43)

How do I make a system like that where I can store rarities with chances? (ex. Basic rarity from 1 to 3 and Legendary from 200 to 500)

local chance = {1,1,1,1,1,2,2,3}
wait()
local chanceresult = chance[math.random(1, #chance)]

youd wanna use a weighted rng system, here’s how you do it:

  • ps. if you need help, I can write the code out for you and give you a gist on how it works.

So let’s break it down.

There need to be three main parts to this script:

  • The RNG
  • The rarity lookup table
  • The decision process

The RNG is simple enough. You can do this with:

local RandomGenerator = Random.new()

You might be wondering why I’m using the Random library as opposed to math.random. This is personal preference, and it doesn’t matter.

Next, the lookup table.

-- These are % chance
local Rarities = {
	["Common"] = 50,
	["Uncommon"] = 20,
	["Rare"] = 15,
	["Epic"] = 5,
	["Legendary"] = 2.5
}

-- Get the MaxRarity value needed for the decision
local MaxRarity = 0
for i, v in Rarities do
	MaxRarity += math.ceiling(v) -- NextInteger doesn't work with floats,
	-- so I will just round up here to make it an int instead.
end

This is simple enough.

And finally, the decision function.

local function DecideRarity(Number)
	local CurrentRarity, BestRarity = nil, math.huge
	
	for i, v in Rarities do
		if v > Number and v < BestRarity then
			-- We also keep track of the best rarity we had in order to
			-- make sure the iterator doesn't go in the wrong order
			CurrentRarity = i
			BestRarity = v
		end
	end
	
	return CurrentRarity 
end

local Rarity = DecideRarity(RandomGenerator:NextInteger(0, MaxRarity))

This is a bit more complex, but what it’s doing is it goes through the table and it finds the best rarity that’s also bigger than the number that got rolled. Then it returns the rarity it got.