Why is my weighted chance system always returing 30?

I am attempting to make a weighted chance system but for some reason my function always returns 30. I get no errors.

here is the function.

local function selectRandomPet(eggNumber)
    local petChanceTable = {}

    for _,v in pairs(PetInfo.EggChances[eggNumber]) do
        table.insert(petChanceTable, v[1])
    end

    table.sort(petChanceTable, function(a, b)
        return a > b
    end)

    local random = math.random(0, 100)

    for _,v in ipairs(petChanceTable) do
        if random <= v then
            return v
        else
           random =- v 
        end
    end
end

here is the table it pulls from

PetInfo.EggChances = {
    [1] = {
        [1] = {10, "SquidBoi"};
        [2] = {20, "SquidBoi"};
        [3] = {30, "SquidBoi"};
        [4] = {40, "SquidBoi"};
    }
}

I don’t know the technical name but you’re just doing the math wrong. I edited your script and ran it multiple times in studio and I got mixed results instead of just 30.

local PetInfo = {};

PetInfo.EggChances = {
	[1] = {
		[1] = {10, "SquidBoi"};
		[2] = {20, "SquidBoi"};
		[3] = {30, "SquidBoi"};
		[4] = {40, "SquidBoi"};
	}
}

local function selectRandomPet(eggNumber)
	local petChanceTable = {}

	for _,v in pairs(PetInfo.EggChances[eggNumber]) do
		table.insert(petChanceTable, v[1])
	end

	table.sort(petChanceTable, function(a, b)
		return a > b
	end)

	local random = math.random(0, 100)

	for _,v in ipairs(petChanceTable) do
		if random <= v then
			return v
		else
			random -= v 
		end
	end
end

print(selectRandomPet(1))

Another thing to remember is to use math.randomseed(tick()), otherwise every instance of the game will return the same “random” numbers in the same exact order every time.

Im pretty sure they patched that

1 Like