Conditionals
Conditionals are used to evaluate statements as true
or false
. They can be used to direct the flow of a program by specifying code blocks to run depending on the outcome of the expression.
The statement or condition can contain logic operators and variables.
If Statements
if <condition> then
<code>
end
if..then
statements run a block of code only when the condition is met. If the condition is false
, the code block inside the if
statement does not run. All conditional statements need to have an end
keyword to close off the statement.
The following example demonstrates an if
statement with a true
condition:
a = 13b = 16if a < b thena = a + 5endprint(a)-- This prints 18 because a is less than b, so the code within the if statement was run which updates the value of a.
The following code block demonstrates when the condition is now false
:
a = 8b = 10if a==b thenprint(b + a)end-- Nothing is printed because a is not equal to b so the code statement was not executed.
Else Statements
if <condition> then
<code>
else
<code>
end
In the event that the first condition is false
, when there’s a subsequent else
statement, the else
statement will execute instead. Think of the else
as an “if all else fails” plan. The else
statement must go at the end and does not have a condition.
isNightTime = falseif isNightTime thenprint("Good night!")elseprint("Good morning!")end-- This statement prints "Good morning!" because the if condition evaluated to false.
ElseIf Statements
if <condition> then
<code>
elseif <condition> then
<code>
else
<code>
end
elseif
statements are similar to else
statements but they can be used to create multiple actions instead of an either/or format. You can have multiple elseif
statements, each with its own condition, but the final statement has to be an else
statement.
player1 = 9player2 = 12if player1 >= 20 and player2 >= 20 thenprint( "Everyone wins!")elseif player1 > player2 thenprint( "Player 1 wins with " .. player1 .. " points!")elseif player1 < player2 thenprint( "Player 2 wins with " .. player2 .. " points!")elseprint ("It’s a tie.")end-- This prints "Player 2 wins with 12 points" because it’s the first statement that evaluates to true.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Lua on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Lua
Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.Beginner Friendly4 hours