How to make a loot table with chances lower than 1% (0.1,0.5,0.8,etc)

Code:

local LootTable = {
    { item = "Sword", chance = 30 },  -- 30% chance of getting a Sword
    { item = "Shield", chance = 20 }, -- 20% chance of getting a Shield
    { item = "Potion", chance = 50 }  -- 50% chance of getting a Potion
}

function chooseItem()
    local totalChance = 0
    for _, entry in ipairs(LootTable) do
        totalChance = totalChance + entry.chance
    end

    local randomChance = math.random(1, totalChance)
    local cumulativeChance = 0

    for _, entry in ipairs(LootTable) do
        cumulativeChance = cumulativeChance + entry.chance
        if randomChance <= cumulativeChance then
            return entry.item
        end
    end
end

-- Example usage: chooseItem() will return a random item based on the chances in the loot table.

local player = game.Players.LocalPlayer
local backpack = player.Backpack

local function giveRandomItem()
    local item = chooseItem()
    local newItem = game.ReplicatedStorage.Items:FindFirstChild(item):Clone()
    newItem.Parent = backpack
end

-- Example usage: Call giveRandomItem() to give the player a random item from the loot table.

How would i make chances lower than 1% bc math.random cannot generate that low

1 Like

Just use Random.new():NextInteger(minimum, max)

i’ve tried idk if its accurate

its less buggy than math.random() from experience

how me how i can implement it into this code

just change all the math.random(min, max) to Random.new():NextInteger(min, max)
one change to your code:

local randomChance = Random.new():NextInteger(1, totalChance)
1 Like

but i think it would be NextNumber bc it needs to be a decimal for 0.8%

Yes it would

chrrrrrrrrrr

But NextNumber has no parameters in the docs
refer to this:


local lootTable = {
  ["Common"] = 0.5, -- 50%
  ["Mythic"] = 0.01 -- 1%, etc.
}

local chosen = math.random()

local totalPercentage = 0
for i, percentage in pairs(lootTable) do
      totalPercentage += percentage
     if chosen <= totalPercentage then
           return i -- this one  is picked
     end
end

something like this should work :slight_smile: you can reverse the keys and values you would have to times by 100

1 Like

Just generate a random number above 100
1/100 = 0.01 or 1 percent
1/1000 = 0.001 or 0.1 percent
1/150 = 0.00666666667 or 0.666666667 percent

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