The if-then-else Statement
Part of the Fundamentals section of Coddy's Lua journey — lesson 41 of 90.
The else block extends the basic if statement by providing an alternative action when the condition is false.
Here's the syntax for an if-then-else statement:
if condition then
-- code to run if condition is true
else
-- code to run if condition is false
endWhen the condition evaluates to true, only the first block runs. When it's false, only the else block runs. This ensures that exactly one of the two blocks will always execute.
Here's a practical example:
local hasKey = true
if hasKey then
print("Door opens")
else
print("Door is locked")
endSince hasKey is true, this will print "Door opens". If hasKey were false, it would print "Door is locked" instead.
Challenge
EasyCreate a door access system that handles both scenarios when a player approaches a locked door. Declare a boolean variable called hasKey and assign it the value false. Use an if-then-else statement to check if the player has the key. If hasKey is true, print "Door opens". If hasKey is false, print "Door is locked".
Cheat sheet
The else block provides an alternative action when the if condition is false.
Syntax for if-then-else statement:
if condition then
-- code to run if condition is true
else
-- code to run if condition is false
endExample:
local hasKey = true
if hasKey then
print("Door opens")
else
print("Door is locked")
endExactly one of the two blocks will always execute - the if block when the condition is true, or the else block when it's false.
Try it yourself
-- Declare the hasKey variable
local hasKey = false
-- TODO: Write your code here to check if the player has the key and print the appropriate messageThis 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