Menu
Coddy logo textTech

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 hasWeapon

Similarly, 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 hasPassword

Cheat 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 hasWeapon

For 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 hasPassword

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals