Get random value with chances

im making a roll system where u can get races but with rarites and im having a problem when i print the chosen race its nil and i dont know how to fix and i i would very appreciate if someone could help me thanks ahead

local playerstats = game.Players.LocalPlayer:WaitForChild("playerstats")
local value = playerstats:WaitForChild("Race")

local races = {
	"Human",
	"Giant",
	"Fairy",
	"Goddess",
	"Demon",
}

local chances = {
	["Human"] = 79.86;
	["Giant"] = 11.27;
	["Fairy"] = 6.89;
	["Goddess"] = 1.02;
	["Demon"] = 0.96;
}

local choose = function()
	local randomNumber = math.random(1, 100)
	local counter = 0

	for rarity, weight in pairs(chances) do
		counter = counter + weight
		if randomNumber <= counter then
			local raritytable = races[rarity]
			local chosenrace = raritytable[math.random(1, #raritytable)]
			print(chosenrace)
			return chosenrace
		end
	end
end

script.Parent.MouseButton1Click:Connect(function()
	local chosenRace = choose()
	if chosenRace then
		value.Value = chosenRace
	end
end)

1 Like

The races table is actually indexed by numbers (1, 2, 3,4 ,5) and you’re trying to index it by a string when you do races[rarity]. It should error on the next line when you try to index nil.

1 Like

so i should just give the races a number?

edit: i fixed the error but it still comes out as nil

1 Like

This script reminds me of something ChatGPT would write. It usually creates useless variables or uses made up API and wrong syntax…
anyway you should probably do

if randomNumber <= counter then
   print(rarity)
   return rarity
end

that’s all you need

3 Likes

tysm it works now


3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.