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

How do I define what math.random was chosen?

Asked by 9 years ago

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.

1 answer

Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

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
  • Remember that == means "is" and ~= means "is not"
  • Remember to tab your code correctly
  • Remember to use local to define new variables
  • math.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"

  1. 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

  2. Pure functions are usually easier to reason about. For things like randomness, it's often much more convenient to produce different values. 

Ad

Answer this question