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?
This is one way you could do it:
1 | local var 1 = math.random(- 5 ,- 1 ) |
2 | local var 2 = math.random( 1 , 5 ) |
3 | local var 3 = math.random( 1 , 2 ) |
4 | local finalVar = 0 |
5 | if var 3 = = 1 then |
6 | finalVar = var 1 |
7 | elseif var 3 = = 2 then |
8 | finalVar = var 2 |
9 | end |
or you could do it this way:
01 | function chooseVar() |
02 | finalVar = math.random(- 5 ,- 1 ) |
03 | return finalVar |
04 | end |
05 |
06 | repeat |
07 | if finalVar > = - 1 and finalVar< = 1 then |
08 | chooseVar() |
09 | end |
10 | until finalVar > = 1 or finalVar< = - 1 |
11 |
12 | print (finalVar) --just to make sure this worked correctly |
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
1 | 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