Math.random is not working for me

For some reason the script I made will never print the result 2. Why does this happen?
Code:
local z = math.random(1 , 2)
while wait(1) do
if z == 1 then
print(1)
elseif z == 2 then
print(2)
end
end

I am not very good at scripting, but I assume it’s due to the two equal signs? Maybe only do one.

1 Like

Are you sure it’s not working? It could be the fact that it’s random and you just got unlucky. Also that code is a bit inefficient.

1 Like

No, the equal signs are correct. He is saying that it wont print the second result meaning it does print the first.

2 Likes

You have to add quotation marks around “1” and “2” for the prints.

1 Like

try math.random(1,3)
also, try putting the declaration of z in the while loop so it changes

1 Like

Not really, as shown here:
image


gives the same result

Put the math.random in the loop to make the result different

while true do
	wait(1)
	local z = math.random(1, 2)
	print(z)
end

Changing math.random(1, 2) to math.random(2) would do the same thing if you’re curious as giving only 1 argument would treat it the minimum as 1 and the maximum as the number you gave it

3 Likes

Result:

My bad on that one. :sweat_smile:
I think @EmbatTheHybrid was the solution.

2 Likes

Looks like the problem was there (I haven’t played with scripts in a while so I’ve been a little forgetful, thanks)

1 Like

Math.Random is pseudo-random (meaning “appears to be random”), though it returns a digit between the specified minimum and maximum range. A result of 2 is still possible like Embat shared via a loop though I believe the cause of it being 1 most often is likely due to how the method is retrieving the result on script execution and only executing once.

I would suggest you actively try to use Math.random for a larger range of numbers than what you’ve done as it would lead to a greater chance of variety, even if it’s not truly random.

Source - Lua Docs - math
image

1 Like