Picking a random variable

I am making a game and I want to know how to set the ‘ChosenVariable’ to something random:

local test = 1
local test2 = 2
local test3 = 3
local ChosenVariable = (One of the three)

So how do I make it so ChosenVariable has a 33% chance to equal 1 2 or 3?

5 Likes
local randomVars = {1, 2, 3} -- put the variables in a table
local randomVar = randomVars[math.random(#randomVars)] -- picking a random variable from the table
print(randomVar)
randomVar = randomVars[math.random(#randomVars)]
print(randomVar) 

Hope this helps! :slight_smile:

10 Likes

Do you want to choose a random variable? Or a random number? Because math.random() gets the maximum and minimum number. So you can just generate a random number between the range.

local randomNum = math.random(1,3)
print(randomNum)

I want it to choose a random variable, then set ‘RandomVariable’ to the value of that random chosen variables

Also, I just used the test things as an example, It would have been like this:

local virus1 = "Cold"

Would It make a difference if it was text?

Then you can do what @changeno did, put the variables in a table and pick a random one.

For variables, just replace the numbers with the variables.:

local test1 = 1
local test2 = 4
local test3 = 8
local varTable = {test1, test2, test3}
local randomVar = varTable[math.random(#varTable)]

I hope this helps you:

local variables = {1, 2, 3}
local ChosenVariable = variables[math.random(1, #variables)]
print (ChosenVariable)

Wish you luck in the future :slight_smile:

1 Like

Could I do this:

local variables = {"Hi", "Hello", "Salutations"}
local ChosenVariable = variables[random(1, #variables)]
print (ChosenVariable)
1 Like

I tested this in-game and it worked for me:

local Variable1 = 5
local Variable2 = 50
local Variable3 =  100

local Variables = {
Variable1,
Variable2,
Variable3,
}

local randomVariable = Variables[math.random(1,#Variables)]
print(randomVariable)

Hope it helps! (This is a regular script btw)

Yes u can. the stuff inside the {} can be anything

1 Like

Yeah, I believe so. (30 charrrrrrrrrrrrrrrrrr)