Short-Circuit Evaluation
Part of the Fundamentals section of Coddy's Lua journey — lesson 23 of 90.
and and or operators, it uses a clever optimization called short-circuit evaluation. This means Lua stops evaluating as soon as it knows the final result, potentially skipping parts of the expression entirely.
For the and operator, if the first condition is false, Lua immediately knows the entire expression will be false without checking the second condition:
playerAlive = false
hasWeapon = true
canFight = playerAlive and hasWeapon
-- Lua only checks playerAlive (false), never evaluates hasWeaponSimilarly, for the or operator, if the first condition is true, Lua knows the result will be true and skips the second condition:
hasKey = true
hasPassword = false
canEnter = hasKey or hasPassword
-- Lua only checks hasKey (true), never evaluates hasPasswordCheat sheet
Lua uses short-circuit evaluation for and and or operators, stopping evaluation as soon as the final result is known.
For and operator: if the first condition is false, the second condition is never evaluated:
playerAlive = false
hasWeapon = true
canFight = playerAlive and hasWeapon
-- Only checks playerAlive (false), skips hasWeaponFor or operator: if the first condition is true, the second condition is never evaluated:
hasKey = true
hasPassword = false
canEnter = hasKey or hasPassword
-- Only checks hasKey (true), skips hasPasswordTry it yourself
This lesson doesn't include a code challenge.
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