Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I define what math.random was chosen?

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

✓ Accepted answer

Each time you call math.random, it will give you a new number[^1]. 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 it[^2].

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

This discussion is preserved as it was. New answers, comments, and votes are closed.