Lua if...else Statement
if...else Statement
Lua if statements can be used in conjunction with else statements to execute a block of code when the if condition expression is false.
The syntax for Lua if...else statements is as follows:
if(boolean expression)
then
--[ Block of code to be executed if the boolean expression is true --]
else
--[ Block of code to be executed if the boolean expression is false --]
end
When the boolean expression is true, the code block within the if statement is executed; when the boolean expression is false, the code block within the else 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 for the if statement is as follows:
Example
The following example checks the value of variable a:
--[ Define variable --]
a = 100;
--[ Check condition --]
if( a < 20 )
then
--[ Block of code to be executed if the condition is true --]
print("a is less than 20" )
else
--[ Block of code to be executed if the condition is false --]
print("a is greater than 20" )
end
print("The value of a is :", a)
The output of the above code is:
a is greater than 20
The value of a is : 100
if...elseif...else Statement
Lua if statements can be used in conjunction with elseif...else statements to execute a block of code when the if condition expression is false, and to check multiple condition statements.
The syntax for Lua if...elseif...else statements is as follows:
if( boolean expression 1)
then
--[ Block of code to be executed if boolean expression 1 is true --]
elseif( boolean expression 2)
then
--[ Block of code to be executed if boolean expression 2 is true --]
elseif( boolean expression 3)
then
--[ Block of code to be executed if boolean expression 3 is true --]
else
--[ Block of code to be executed if none of the above boolean expressions are true --]
end
Example
The following example checks the value of variable a:
--[ Define variable --]
a = 100
--[ Check boolean conditions --]
if( a == 10 )
then
--[ Print this message if the condition is true --]
print("The value of a is 10" )
elseif( a == 20 )
then
--[ Print this message if the elseif condition is true --]
print("The value of a is 20" )
elseif( a == 30 )
then
--[ Print this message if the elseif condition is true --]
print("The value of a is 30" )
else
--[ Print this message if none of the above conditions are true --]
print("No match for the value of a" )
end
print("The actual value of a is: ", a )
The output of the above code is:
No match for the value of a
The actual value of a is: 100