Can't understand why this table iteration skips the first value

hi, for this to work the weights must be ordered. This should work

Pets = game.ReplicatedStorage.Pets

local petModule = {}

petModule.pets = {
	
	["Legendary"] = {
		Pets.Bee;
	};
	
	["Epic"] = {
		Pets.Bat;
	};
	
	["Rare"] = {
		Pets.Dog;
	};
	
	["Common"] = {
		Pets.SurprisedGhost;
		Pets.ContentGhost
	};		
	
}

-- Weighted selection
petModule.rarities = {
	
	[5] = "Legendary"; -- 5% chance
	
	[15] = "Epic"; -- 15% chance
	
	[30] = "Rare"; -- 30% chance
	
	[50] = "Common"; -- 50% chance
	
}

petModule.chooseRandomPet = function()
		
	local randomNumber = math.random(1,100)
	
	-- ordered weights required
	local raritiesWeights = {}
	for value, _ in pairs(petModule.rarities) do
		table.insert(raritiesWeights, value)
	end
	table.sort(raritiesWeights)
	

	local counter = 0
	local rarity
	
	print("RandomNum "..randomNumber)
	
	for _, weight in ipairs(raritiesWeights) do
		rarity = petModule.rarities[weight]
		counter = counter + weight
		
		print ("Weight "..weight)
		print ("Counter "..counter)
		
		if randomNumber <= counter then
			
			print ("InCounter "..counter)
			
			print ("InRandomNum "..randomNumber)
			print ("Choosen Rarity "..rarity)
			
			local rarityTable = petModule.pets[rarity]
			local chosenPet = rarityTable[math.random(1,#rarityTable)]
			
			return chosenPet
			
		end
	end	
end

return petModule

I also changed the table petModule.rarities

2 Likes