How to make rarity chance only pick 1 item?

So I need help with only choosing 1 item depending on the rarity.

local function RandomChance()
	local TotalWeight = 0

	local moneyTable = {
		{Name = "Penny", Chance = 60},
		{Name = "Dime", Chance = 12},
		{Name = "Quarter", Chance = 3},
		{Name = "GoldCoin", Chance = 1},
	}

	for i,v in ipairs(moneyTable) do
		TotalWeight += v.Chance
	end

	local Chance = math.random(0, TotalWeight)
	local Counter = 0

	for i,v in ipairs(moneyTable) do
		Counter += v.Chance

		if Counter <= Chance then
			print(v)
		end
	end
end

This will sometimes pick more than 1.

1 Like

The issue is that when the random number generated is between the sum of the weights of two items, both items are printed. To fix this, you need to break the loop after printing the selected item.

try this:

local function RandomChance()
	local TotalWeight = 0

	local moneyTable = {
		{Name = "Penny", Chance = 60},
		{Name = "Dime", Chance = 12},
		{Name = "Quarter", Chance = 3},
		{Name = "GoldCoin", Chance = 1},
	}

	for i,v in ipairs(moneyTable) do
		TotalWeight += v.Chance
	end

	local Chance = math.random(0, TotalWeight)
	local Counter = 0

	for i,v in ipairs(moneyTable) do
		Counter += v.Chance

		if Counter >= Chance then
			print(v.Name)
			break
		end
	end
end
2 Likes

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