Easy Tutorial
❮ Lua Garbage Collection Home ❯

Lua if Statement

Lua Decision Making

The Lua if statement consists of a boolean expression as a condition, followed by other statements.

Syntax of Lua if Statement:

if(boolean expression)
then
   --[ Statements to execute if the boolean expression is true --]
end

The code block within the if statement is executed if the boolean expression is true. If the boolean expression is false, the code following the end of the if statement is executed.

Lua considers false and nil as false, and true and non-nil as true. Note that in Lua, 0 is considered true.

The flowchart of the if statement is as follows:

Example

The following example checks if the value of variable a is less than 20:

Example

--[ Define variable --]
a = 10;

--[ Use if statement --]
if( a < 20 )
then
   --[ Print the following message if the condition is true --]
   print("a is less than 20" );
end
print("The value of a is:", a);

The output of the above code is:

a is less than 20
The value of a is: 10

Lua Decision Making

❮ Lua Garbage Collection Home ❯