Math.Random Rarity

How do I use math.random to create a rarity of tables which can be spun for?
Not sure if that’s how it works.
An example would be;

If you’re playing a anime game and you reroll your Magic for a rarer magic.

1 Like

One way you could do it is to first give every object in the table a rarity value (0 - 100 all rarity values have to add up to 100) then you can do the following

  1. Generate a random number from 1 - 100
  2. User a for loop to check if the number generated is larger or smaller than the rarity value of the current list item (If the generated number is larger than the rarity value then you continue looping through the array if not you stop and return the current list item)

NB! The rarity values have to be in ascending order

--Example rarity
-- The rarity of the item is the change from the last rarity value to the current one
local items = {
    {Name = "Something", Rarity = 10}, -- 0 -> 10 = 10%
    {Name = "Something2", Rarity = 20}, -- 10 ->  20 = 10%
    {Name = "Something3", Rarity = 30}, -- 20 -> 30 = 10%
    {Name = "Something4", Rarity = 40}, -- 30 -> 40= 10%
    {Name = "Something5", Rarity = 50},
    {Name = "Something6", Rarity = 60},
    {Name = "Something7", Rarity = 70},
    {Name = "Something8", Rarity = 100}, -- 70 -> 100 = 30%
}

function PickRandom()
    local RandomNumber = math.Random(100)

    for _, item in pairs(items) do
        if item.Rarity < RandomNumber then
            return item
        end
    end
end

2 Likes
local magics = {"Light","Dark","Nature"}
local function spin()
    return magics[math.random(1,#magics)]
end
print(spin())
print(spin())
1 Like