Math.Random Only working first loop

  1. What do you want to achieve? Keep it simple and clear!
    Im trying to make the scale field in my script randomise between the two numbers each time PickRandom is called
  2. What is the issue? Include screenshots / videos if possible!
    When calling the field the Math.Random works the first time but not the rest.
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    Ive looked on alot of related math.random threads on developer hub but nothing has solved my issue.


image
If you see the scale is the same where I want it to be different every time. when printing the table to the output

If you want the rarities of the values in sizerarity to be randomised each time you call PickRandom, you’ll need to redefine the variable within the function. The math.random() thing is only called once initially when first setting up the table, causing the value to become constant during runtime.


Alternatively, store the upper and lower bounds of math.random in a table, then just call math.random() on it during the function, so you don’t have to redefine the table each time

1 Like

I believe your issue is based on your v.Chance because it’ll return V as soon as the first one is met, Making the first match occur. I recommend

function PickRandom()
    local RandomNumber = math.random(100)
    local cumulativeChance = 0

    for _, v in pairs(sizerarity) do
        cumulativeChance = cumulativeChance + v.Chance
        if RandomNumber <= cumulativeChance then
            return v
        end
    end
end

The changes I added are to change from comparing each chance directly it should iterate them through the table.

basically if a random number is generated, this loop will iterate it adding each entry chance to the cumulativechance. and if it falls in your range it SHOULD give the return.

1 Like

This strategy will work, but, you must replace the pairs with ipairs so that the rarity categories are iterated in most to least common order just as they are authored in the table. Because Lua’s pairs does not guarantee that the array will be iterated, it’s possible even for Ancient to end up being less rare than Common. Right now, you may not see this happen, but it definitely can, and the Roblox is free to change the iteration order of pairs at any time (even completely randomize it) if there is some optimization that benefits from it. ipairs on an ordered array will always work and be futureproof.

2 Likes

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