• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

[Function] Choose element by chance

zbizu

Legendary OT User
Joined
Nov 22, 2010
Messages
3,323
Solutions
26
Reaction score
2,694
Location
Poland
this function chooses one random element based on their chance to appear

input:
Code:
-- chances must be integers!
selectByChance({element1, element2, ...}, {chance1, chance2, ...})

output:
Code:
elementx

function:
Code:
function selectByChance(elements, chances)
    if #elements ~= #chances then
        return elements[math.random(1, #elements)]
    end
   
    local maxChance = 0
    for i = 1, #chances do
        maxChance = maxChance + chances[i]
    end
   
    local roll = math.random(1, maxChance)
    local chance = 0
    for i = 1, #elements do
        chance = chance + chances[i]
        if roll <= chance then
            return elements[i]
        end
    end
end
 
Back
Top