Operators tutorial

Operators are one of the basic programming tools, used in any programming language; at many of tutorials operators is second place after variables.
Neverthless i often see people having troubles with them.

This is article from documentation but with more examples and explaining


Definition: “An operator is a symbol for performing an operation or conditional evaluation.”
Basically function which making something with data or checking condition



What is evaluating as true and false?

Before learning operators we should understand exactly what evaluating as true and false

  • Firstly, obviosly true == true and false == false
  • Also nil == false. That’s because nil does not exist. nil represents nothingness.
  • All existing in game instances is true. You can’t make instance false
  • Any other data (Number, Vector3, string etc.) is true

This can be united to one statement:
Anything except nil or false is true

Examples
-- This part existing in workspace, so it's true
local Part = workspace.MyPart

if Part then
	print("Part exists") -- Part exists
end
-- Number evaluating as true
local Number = 42

if Number then
	print("Number is true") -- Number is true
end


Logical

Generally they used in if -- then for checking conditions, but also can be very useful to get value depending on conditions (worst explanation ever)

There’s 3 of them:

and
Returns true only if both conditions is true

Example
local UltraCondition = true
local Part = workspace.MyPart

if Part and UltraCondition then --Both Part and UltraCondition is true
	print("Nothing wrong")
else                            --If something is false or nil
	print("Something is missing")
end

--Prints Nothing wrong

or
Returns true if at least 1 of conditions is true

Example
local Boolean = false
local Part = workspace.MyPart

if Part or Boolean then
	print("Nothing wrong")
else
	print("Nothing exists!")
end

--Prints Nothing wrong

not
Returns opposite of condition

Example
print(not true) --false
print(not nil) --true
print(not workspace) --false
print(not 5) --false
print(not "Hi") --false

Using to set variables

Many of people doesn’t understand how this works.
Here’s the second operators descriptions:

Operator Description
And Returns one of the two arguments. If the first argument is true, then it returns the second argument. Otherwise, it returns the first argument.
Or Returns one of the two arguments. If the first argument is true, then it returns the first argument. Otherwise, it returns the second argument.
Not Returns the opposite boolean value of the argument. If the argument is false or nil, then it returns true. Otherwise, it returns false.

That is:

local WantCereals = "Yes"
local Spaghetti = "Spaghetti"
local Cereals = "Cereals"

local Breakfast = WantCereals and Cereals or Spaghetti
print(Breakfast)
--Prints cereals
--If wantcereals then "and" operator returns cereals
--If cereals exists then "or" operator returns cereals

This can be showed at more straight way

if WantCereals and Cereals then
	Breakfast = Cereals
else
	Breakfast = Spaghetti
end

print(Breakfast)
--Prints cereals
--Because cereals is exists and you want cereals

But where we can use this?
To check if value not equal to zero!
If you tried to make custom movement systems you may encountered trouble if humanoid’s
move direction is zero (for example). And if you try to set NaN value somewhere, game’ll break
(especially if do this every render step).
You can use this to solve this problem

local Velocity = MoveController.Direction
if Velocity ~= LinearVelocity.VectorVelocity then
	Velocity = Velocity.Magnitude ~= 0 and Velocity.Unit or Velocity --We interested at this piece
	LinearVelocity.VectorVelocity = Velocity * 16
end

This is piece of my swimming controller
Before i added third line, if i just stop moving, code’ll try to get unit of Vector3.zero.
And this crashed my game.
How this works:

Is velocity magnitude == 0?
No → Make unit of velocity and return Yes → Return just velocity

**Don’t too hard right?**‎



Relational

They’re compare two parameters and return a boolean: true or false.

Operator Description Example Associated metamethod
== Equal to 3 == 5 → false __eq
~= Not equal to 3 ~= 5 → true
> Greater than 3 > 5 → false
< Less than 3 < 5 → true __lt
>= Greater than or equal to 3 >= 5 → false
<= Less than or equal to 3 <= 5 → true __le
More realistic examples

This UserId mine

local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(Player)
	if Player.UserId == 1612372923 then
		print("You owe me money carl")
	end
end)

Amount of people in space

local HttpService = game:GetService("HttpService")

local Data = HttpService:GetAsync("http://api.open-notify.org/astros.json") --People in space now
Data = HttpService:JSONDecode(Data)

if Data.number > 5 then
	print("There are more than 5 people in space right now")
end


Arithmetic

Operator Description Example Associated metamethod
+ Addition 1 + 1 = 2 __add
- Subtraction 1 - 1 = 0 __sub
* Multiplication 5 * 5 = 25 __mul
/ Division 10 / 5 = 2 __div
// Floor Division 10 // 4 = 2-10 // 4 = -3 __idiv
^ Exponentiation 2 ^ 4 = 16 __pow
% Modulus 13 % 7 = 6 __mod
- Unary negation -2 = 0 - 2 __unm

The most incomprehensible is floor division, modulus and unary negation
Floor division
It divides a value by another value and returns an integer that is less or equal to the result of the division.

local X = 50

print(X // 4) -- 12

-- Equal to

local Y = X / 4
local Z = math.floor(Y)

print(Y) -- 12.5
print(Z) -- 12

Modulus
It returns remainder of division

local X = 12
local Y = 7

print(X % Y) -- 5


-- Equal to


-- Can 12 be substracted by 7 without negating?
-- Yes

X -= Y

print(X) -- 5

-- Can 5 be substracted by 7 without negating?
-- No
-- Return 5

Unary Negation
Inverting value / makes opposite sign

print(-1) -- -1
print(-4) -- -4
print(-Vector3.new(1,15,4)) -- -1, -15, -4
print(-"-42") -- 42
print(-true) -- error


Compound assignment

The same as arithmetic but more beautiful

Operator Operation Example New Value
+= Addition 3 += 2 5
-= Subtraction 3 -= 2 1
*= Multiplication 3 *= 2 6
/= Division 3 /= 2 1.5
//= Floor Division 3 //= 2 1
%= Modulus 3 %= 2 1
^= Exponentiation 3 ^= 2 9
..= Concatenation 3 ..= " World!" "3 World!"
local Money = 15
local Noodles = "45"

Money *= 10
Noodles -= 8

print(Money) -- 150
print(Noodles) -- 37



Miscellaneous

Operator Description Associated metamethod
.. Concatenates two strings or numbers __concat
# Length of table or amount of characters in string __len
local A = 1
local B = 5
local C = "C"
local D = "4"

print(A..B) -- 15
print(A..D) -- 14
print(A..C) -- 1C
print(C..D) -- C4
print(B..D) -- 54
print(B..C) -- 5C
local List = {"Oleg", "John", "Anna", "Belle"}
local str = "Glued boots"

print(#List) -- 4
print(#str) -- 11 (space is also symbol)


Questions you may have:

nil is absense of value. It’s doesn’t exist.
false It’s almost same as nil but exists and consume memory

if Condition == true then is the same as if Condition then
Thats because it checks condition existstance. (Very simplificated)

Besides numbers, you can apply almost all arithmetic operators on String, Vector3, Vector2
print("5" * 3) -- 15

Read about metamethods: All you need to know about Metatables and Metamethods



Funny script

This scripts creates invisible and non-existing wall 50 studs from center on X axis
Train youself and explain how it works

Yes, i know it can be easily done with math.clamp()

--LocalScript inside StarterCharacterScripts
local HumanoidRootPart:Part = script.Parent:WaitForChild("HumanoidRootPart")
local RunService = game:GetService("RunService")

RunService:BindToRenderStep("Limit",  199, function()
	local XPos = HumanoidRootPart.CFrame.Position.X <= 50 and HumanoidRootPart.CFrame.Position.X or 50
	HumanoidRootPart.CFrame = CFrame.new(XPos, HumanoidRootPart.CFrame.Position.Y, HumanoidRootPart.CFrame.Position.Z) * HumanoidRootPart.CFrame.Rotation
end)

That’s all

I hope you learned much
Good luck, good scripting

Let me know if you want to add info or i explained something bad.
And sorry for the grammar mistakes.

3 Likes

You should explain why Part evaluates to true and talk about truthy and falsy values.

2 Likes

Yeah, thank you for the note. I’ll add it soon