Chapter 0.3: Operators - The Tools of Logic
Variables store information, but operators are the tools that let you work with that information. They are the verbs of our programming language.
Arithmetic & Assignment Operators
These are for doing math and assigning values. A common mistake is confusing = (assignment) with == (comparison).
score = 10is a command: "Set thescorevariable to 10."score == 10is a question: "Is thescorevariable equal to 10?"
Shorthands and Other Useful Operators
Programmers love shortcuts. Here are a few common ones:
- Shorthand Assignment:
x += 5is the same asx = x + 5. This works for-=,*=, and/=as well. - Incrementing:
i++is the same asi = i + 1. You'll see this constantly inforloops. - Modulo (
%): This gives you the remainder of a division. It's surprisingly useful for checking if a number is even or odd.10 % 2is0(even), while11 % 2is1(odd).
Comparison Operators
These operators ask a question and always result in a true or false value.
// Example Comparisons
local score = 100
local requiredScore = 150
local cubes = 2
local isScoreEnough = (score >= requiredScore) // isScoreEnough is now false
local areCubesCorrect = (cubes == 2) // areCubesCorrect is now true
local isNotEnough = (score != requiredScore) // isNotEnough is now true
Logical Operators
These are the most powerful operators. They let you combine multiple true/false conditions to make complex decisions.
&&(AND): Returnstrueonly if the conditions on both sides are true.||(OR): Returnstrueif at least one of the conditions is true.!(NOT): Inverts a boolean value. It turnstrueintofalse, andfalseintotrue.
local cubeIsOnButton = true
local laserIsDisabled = false
// AND Example: The bridge will only extend if BOTH conditions are met.
if (cubeIsOnButton && laserIsDisabled)
{
// This will NOT run, because laserIsDisabled is false.
}
// OR Example: The alert will sound if EITHER condition is met.
if (!cubeIsOnButton || !laserIsDisabled)
{
// This WILL run, because !laserIsDisabled is true.
}