Equality Operators
Part of the Fundamentals section of Coddy's Lua journey — lesson 18 of 90.
Equality operators. These operators allow you to compare two values to determine if they are the same or different.
Lua provides two equality operators:
userGuess = 42
secretNumber = 42
isCorrect = userGuess == secretNumber -- isCorrect is true
playerName = "Alice"
targetName = "Bob"
isDifferent = playerName ~= targetName -- isDifferent is trueThe == operator checks if two values are equal, while the ~= operator checks if they are not equal. Notice that the result of these comparisons is always a boolean value - either true or false.
Challenge
EasyCompare a user's guess with a secret number to determine if they match. Create a variable called userGuess and assign it the value 42. Create another variable called secretNumber and assign it the value 37. Use the equality operator to check if the guess equals the secret number, storing the result in a variable called isCorrect. Print the boolean result.
Cheat sheet
Lua provides two equality operators for comparing values:
==checks if two values are equal~=checks if two values are not equal
Both operators return a boolean value (true or false):
userGuess = 42
secretNumber = 42
isCorrect = userGuess == secretNumber -- isCorrect is true
playerName = "Alice"
targetName = "Bob"
isDifferent = playerName ~= targetName -- isDifferent is trueTry it yourself
-- Create variables for the guessing game
-- TODO: Write your code here
-- Print the result
print(isCorrect)This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators 2 Relational & Logic
Equality OperatorsRelational OperatorsThe 'and' OperatorThe 'or' OperatorThe 'not' OperatorShort-Circuit EvaluationTruthy and Falsy ValuesRecap - Simple Logic7Basic Conditional Logic
The if-then StatementThe if-then-else StatementThe elseif StatementRecap - Treasure Chest2Variables and Data Types
What is a Variable?NumbersStringsBooleansThe Value 'nil'The type() FunctionNaming ConventionsRecap - Character Profile5Basic Output
Printing LiteralsPrinting VariablesPrinting Multiple ValuesCombining Strings & VariablesThe tostring() FunctionInputCastRecap - Status ReportRecap - Till 1208String Manipulation Basics
string.len()string.upper & string.lowerstring.sub()string.rep()string.find()Recap - Format Username3Operators 1 Arithmetic & Conc
Arithmetic OperatorsModulo OperatorExponentiation OperatorString ConcatenationOperator PrecedenceRecap - Simple Calculations6Project: Character Stats Disp
Welcome MessageDeclare Character Stats9Functions Basics
Declaring a FunctionCalling a FunctionFunctions with ParametersFunctions with Multiple ParamsThe 'return' StatementRecap - Area Calculator