What I'm trying to use is
print (math.random(1, 2)) if math.random(1, 2)) ~= 1 then message = Instance.new("Message") message.Text = "1 was chosen!" end end
It is printing which number is chosen, but not doing what I am telling it to do when it is chosen.
I am getting no errors, help me please.
Each time you call math.random
, it will give you a new number1. If you want to keep the same number, you need to save it to a variable:
local choice = math.random(1, 2) print(choice) if choice == 1 then local message = Instance.new("Message, workspace) message.Text = "1 was chosen" end
==
means "is" and ~=
means "is not"local
to define new variablesmath.random(n)
is short hand for math.random(1, n)
Also, if you're just going to say "x was chosen" for each number, there's no reason to use an if
at all:
local choice = math.random(2) local message = Instance.new("Message", workspace) message.Text = choice .. " was chosen"
Often when you have computations, you can pull out a value and replace that value for the computation. E.g., math.sqrt(4)
and 2
are always going to be interchangeable because math.sqrt
always returns the same thing. This is called referential transparency. Because of this property, we say that math.sqrt
a pure function. math.random
is NOT a pure function, because it changes each time you call it2. ↩
Pure functions are usually easier to reason about. For things like randomness, it's often much more convenient to produce different values. ↩