Explain how this chance system works

Hi, I’m wondering how this system works, can someone explain?

local Items = {
    {"Table",1},
    {"Lamp",5},
    {"Chair",10},
}
local TotalWeight = 0

for _,ItemData in pairs(Items) do
    TotalWeight = TotalWeight + ItemData[2]
end

local function chooseRandomItem()
    local Chance = math.random(1,TotalWeight)
    local Counter = 0
    for _,ItemData in pairs(Items) do
        Counter = Counter + ItemData[2]
        if Chance <= Counter then
            return ItemData[1]
        end
    end
end

for i=1,10 do
    print(chooseRandomItem())
end

I understand that [1] is the name, [2] I don’t quite understand the number that should fall out to get [1]?

The total weight in your case is 16, meaning that there is a 1/16 chance you get Table.

2 Likes

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