Trouble with For loops & Random Number

Hi There thanks for clicking to help :smiley:

(Note Idk if its the right heading sorry if it is not. )

I want the for loop to match the random number with the lowest number first, but it doesn’t seem to work.

Help here pls

As you can see in this screenshot if the numbers are 1 then it just Chooses the “Bunny Pet”, and I need it to choose the “Fox Pet”.

local RS = game:GetService("ReplicatedStorage")
local Tier1 = RS:FindFirstChild("Tier1")
local PetsFolder = RS:WaitForChild("Pets")

Tier1.OnServerEvent:Connect(function()
	
	local PetWeight = {
		['FoxWeight'] = 1,
		['BearWeight'] = 4,
		['BullWeight']  = 10,
		['BunnyWeight'] = 15,
		['DogWeight'] = 20,
		['CatWeight'] = 50,
		
		
		
	}
	
	local Pets = {
		Bear = PetsFolder.Bear,
		Bull = PetsFolder.Bull,
		Bunny = PetsFolder.Bunny,
		Cat = PetsFolder.Cat,
		Dog = PetsFolder.Dog,
		Fox = PetsFolder.Fox
	}
	
	local Number = math.random(1, 100) ---- Get a random number between 1 and 100
	
	for i,PetWeight in pairs(PetWeight) do
		
		local Counter = 0
			Counter = Counter + PetWeight
		if Number <= Counter then
			print(i.. " " .. Number)
			
			return
		end
	end
	
	
end)

I tried to see if it works in the order the table is written and it didn’t fix the issue, I even tried to see if it reads the table in alphabetical order and yet it still didn’t work.

Is there anyone who can please help me. I’ve been struggling with this for almost an hour now.

Thank You!

Never mind. Ill just add if statements to fix this script :smiley:

Did you know that you are adding 0 to a table?

You will need to get the index of the table so that you can get the number for each weight:

Why are you checking if the number is less than or equal to counter here?

if Number <= Counter then
			print(i.. " " .. Number)
			
			return
		end

Also you’re generating a number from 1 to 100? when your highest pet weight is 50?

I see the problem xD
I need to move the counter outside the for loop xD

Yup, because you are setting it to 0 everytime the for loop runs.

1 Like

lol thanks didnt think about that xD

Because the total of them all are 100 and if I make it 50 then it will mess the chances up.