The if-then Statement
Part of the Fundamentals section of Coddy's Lua journey — lesson 40 of 90.
The if-then-end statement is the foundation of conditional logic in Lua.
An if statement allows your program to execute code only when a specific condition is true. Here's the basic syntax:
if condition then
-- code to run if condition is true
endThe condition can be any expression that evaluates to true or false. If the condition is true, the code inside the block runs. If it's false, the code is skipped entirely.
Here's a practical example:
local score = 85
if score > 80 then
print("Great job!")
endIn this case, since 85 is greater than 80, the condition score > 80 evaluates to true, so "Great job!" will be printed. If the score were 75, nothing would happen because the condition would be false.
Challenge
EasyCreate a simple achievement system that checks if a player's score qualifies for a congratulations message. Declare a variable called playerScore and assign it the value 95. Use an if-then-end statement to check if the score is greater than 90. If the condition is true, print the message "Congratulations! You achieved a high score!".
Cheat sheet
The if-then-end statement executes code only when a condition is true:
if condition then
-- code to run if condition is true
endExample with a comparison:
local score = 85
if score > 80 then
print("Great job!")
endThe condition can be any expression that evaluates to true or false. If true, the code block executes; if false, it's skipped.
Try it yourself
-- Declare the playerScore variable
local playerScore = 95
-- TODO: Write your code here to check if the score is greater than 90
-- Use an if-then-end statement and print the congratulations 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