Hi, I'd like to know how to make a randomized value. More specifically, a randomized true/false value, but random in general would be nice to know how to do. I would like it to be completely random each time the script is run.
It's just a quick question I'm sure one of you can answer :D Thanks for your time!
There is actually a new datatype called Random
. You can see this in the script editor because it will show up blue, just like print
and then
. To make a new Random generator, you use the .new()
method of the Random datatype.
local RNG = Random.new()
Now, there are two different methods to call on the new random number generator object. First is :NextInteger(LowNumber, HighNumber)
. This will give you an integer value between the Low and High numbers you provide it.
local RandomInt = RNG:NextInteger(0, 10) -- a random integer (no decimals) between 0 and 10
The second is :NextNumber
. This gives you an number value between the Low and High you provide it.
local RandomNum = RNG:NextNumber(0, 10) -- a random number (with decimals) between 0 and 10
To get a random boolean value (true or false), this can be used:
function GetRandomBool() local RNG = Random.new() local Int = RNG:NextInteger(0, 1) return (Int == 1) end
I'm assuming you mean something like this possibly
local Randomized = math.random(0,1) local BoolThing = nil if Randomized == 0 then BoolThing = false elseif Randomized == 1 then BoolThing = true end
@StayToasted the problem with your script is that i'll return the same values everytime its run. Random generation on computers works like a function - it returns the same values when the same parameters are inputed. So what we need to do is change the parameter of the math.random
function, so that its different every time its called. The function to do this is math.randomseed
.
But what do we put into here if we want a number that is different every time? Well, we can enter a few different values. I prefer to use tick()
. tick()
returns the number of seconds that passes since January 1, 1970, so its different everytime its called.
So StayToasted's script should look like this:
math.randomseed(tick()) local Randomized = math.random(0,1) local BoolThing = nil if Randomized == 0 then BoolThing = false elseif Randomized == 1 then BoolThing = true end