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
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