Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to set limits to math.random?

Asked by 4 years ago

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?

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. killerbrenden 1537 — 4y

3 answers

Log in to vote
0
Answered by
Avoxea 48
4 years ago
Edited 4 years ago

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
0
kind of clunky but gets the job done Avoxea 48 — 4y
Ad
Log in to vote
0
Answered by 4 years ago

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

0
btw i tested it using print densomenso999 11 — 4y
0
So how would I set a number between -5 to -1 and 1 to 5 into a variable. VexTrexYT 28 — 4y
Log in to vote
0
Answered by 4 years ago
Edited 4 years ago
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

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 PureLiteStudio 80 — 4y

Answer this question