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

How does the "or" operator (Small question) work?

Hello!

I made a code using the "or" operator and there's something about this I don't understand.

Here's an example. I have an Int Value which has "1" in its value. With the code below I'd think it should not trigger when it has "1", only when it's 0 or 2.

But, it does print "Hello", even when the value is 1. Can someone explain why this happens? I don't want the code to trigger when it's 1, only when it actually says 0 or 2.

Code I used in this example:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local test = ReplicatedStorage:WaitForChild("Test") -- IntValue with "1" in Value. 

if test.value == 0 or 2 then

print("hello")

end

2 answers

✓ Accepted answer

The or operator evaluates two boolean values (true or false) on it's left and right, and returns true if at least one of them is true.

In your code, the or operator is evaluating test.Value == 0 and 2 as two separate values.

test.Value == 0 is false, since test.value is equal to one and not equal to 0.

2 is equal to true, because whenever a conditional operator evaluates a value that is unequal to nil it will return true. That's why your code is always returning true.

To write your code with the behavior you expect, it should look like this:


local ReplicatedStorage = game:GetService("ReplicatedStorage")
local test = ReplicatedStorage:WaitForChild("Test") -- IntValue with "1" in Value. 

if test.Value == 0 or test.Value == 2 then
	
	print("hello")

end

Now the second value is being evaluated properly, so test.value needs to be equal to 0 or 2 to return true.

2 comments

0

Better explanation

0

Great in-depth answer. Thank you for this!

The 2 conditions separated by "or" must both be complete. They are not related in any way, so you must do this:

if test.Value == 0 or test.Value == 2 then
	print("hello")
end

2 comments

0

Also, make the "V" in "Value" capital

0

Hey! Thanks :)

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