Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to set limits to math.random?

I want to choose a random number between -5 and 5, but I don’t want -1 to 1 to be chosen. How do I set a limit, if that’s even possible?

1 comment

0

I'm not sure if you can do that with math.random. All I know is that there's a minimum choice and a maximum choice. I don't think you can do it with Random.new() either.

3 answers

✓ Accepted answer

This is one way you could do it:

local var1 = math.random(-5,-1)
local var2 = math.random(1,5)
local var3 = math.random(1,2)
local finalVar = 0
if var3 == 1 then
	finalVar = var1
elseif var3 == 2 then
	finalVar = var2
end

or you could do it this way:

function chooseVar()
	finalVar = math.random(-5,-1)
	return finalVar
end

repeat
	if finalVar >= -1 and finalVar<= 1 then
		chooseVar()
	end
until finalVar >= 1 or finalVar<= -1

print(finalVar) --just to make sure this worked correctly

1 comment

0

kind of clunky but gets the job done

you can set limits to math.random doing this

math.random(-5,5)

the first value is the minimum number and the second one is the maximum

2 comments

0

btw i tested it using print

0

So how would I set a number between -5 to -1 and 1 to 5 into a variable.

local number = math.random(1,5)*((math.random(0,1)*2)-1)

This is probably the most simple way to do it, one line and no if statements

1 comment

0

I couldn't tell if you wanted -1 and 1 to be part of it but I assumed so, if you don't want them then just change the 1,5 to a 2,5

This discussion is preserved as it was. New answers, comments, and votes are closed.