How to do RNG correctly?

Hello! I’m working on a game where players collect items around the map, and each item has a different chance of spawning. I’m stuck on the random number generation (RNG) part. For example, if I want one item to have a 50% spawn chance and another to have a 1% chance, how should I structure the arguments in math.random()? Should I use 100 as the second argument, or is there a better way to approach this? Any help would be appreciated!

I wrote a module you can use, in the function parameter, you can provide your own table, or use the default I put.

local module = {}

local LuckValues = {
	["Common"] = 50,
	["Rare"] = 25,
	["Epic"] = 15,
	["Legendary"] = 5,
}

function module:ChooseRandom(random)
	local luckTable = random or LuckValues

	local totalPercentage = 0
	for _, percentage in pairs(luckTable) do
		totalPercentage = totalPercentage + percentage
	end

	local randomNumber = math.random(1, 100)

	local cumulativePercentage = 0

	for rarity, percentage in pairs(luckTable) do
		cumulativePercentage = cumulativePercentage + percentage

		if randomNumber <= cumulativePercentage then
			return rarity
		end
	end

	return "Common"
end

return module
1 Like

Hi, Thanks for the reply. How does the script work because I’m trying to get better at scripting.

I’ll put comments so you can understand, I also removed some unnecessary bits. Here:

local module = {}

--Make a table of luck values
local LuckValues = {
	["Common"] = 50,
	["Rare"] = 25,
	["Epic"] = 15,
	["Legendary"] = 5,
}

--Make a function to fire, with the random parameter for custom tables
function module:ChooseRandom(random : {})
--Get the luck table and generate a number from 1 to 100, this is our percentage.
	local luckTable = random or LuckValues
	local randomNumber = math.random(1, 100)

--Make a variable to add up all the values
	local cumulativePercentage = 0

--Loop through the luck table and add up the cumulative percentage, when we get to the random percentage, get the closest rarity and return it.
	for rarity, percentage in pairs(luckTable) do
		cumulativePercentage = cumulativePercentage + percentage

		if randomNumber <= cumulativePercentage then
			return rarity
		end
	end
-- fall back if something is set up wrong or something went wrong.
	return "Common"
end

-- return the function
return module
3 Likes

Okay, thank you so much for helping.

1 Like