If statement can be followed by an optional else statement, and the statement is executed when the Boolean expression is false.
grammar
The syntax of an if... else statement in the Lua programming language is:
then
--[ statement(s) will execute if the boolean expression is true --]
else
--[ statement(s) will execute if the boolean expression is false --]
end
If the value of the boolean expression is true, then the if code block will be executed, otherwise the else code block will be executed.
Lua programming language assumes that any combination of Boolean true and non-zero values is true, and whether it is a boolean false or zero, then it is assumed to be a false value. But it should be noted that the value of zero in Lua is considered true.
For example:
a = 100;
--[ check the boolean condition --]
if( a < 20 )
then
--[ if condition is true then print the following --]
print("a is less than 20" )
else
--[ if condition is false then print the following --]
print("a is not less than 20" )
end
print("value of a is :", a)
When the above code is built and run, it will produce the following results.
value of a is : 100
if...else if...else statement
The if statement can be followed by an optional else if ... else statement, which is very useful to use to test various conditions for a single if...else if statement.
When using if, else if, else statements, there are several points to remember to use:
- if can have zero or an else , but must be before elseif.
- If after that there can be zero to many else if before else.
- Once an else if is successful, other elseifs will not be tested.
grammar
The syntax of the if...else if...else...else statement in the Lua programming language is:
then
--[ Executes when the boolean expression 1 is true --]
else if( boolean_expression 2)
--[ Executes when the boolean expression 2 is true --]
else if( boolean_expression 3)
--[ Executes when the boolean expression 3 is true --]
else
--[ executes when the none of the above condition is true --]
end
For example:
a = 100
--[ check the boolean condition --]
if( a == 10 )
then
--[ if condition is true then print the following --]
print("Value of a is 10" )
elseif( a == 20 )
then
--[ if else if condition is true --]
print("Value of a is 20" )
elseif( a == 30 )
then
--[ if else if condition is true --]
print("Value of a is 30" )
else
--[ if none of the conditions is true --]
print("None of the values is matching" )
end
print("Exact value of a is: ", a )
When the above code is built and run, it will produce the following results.
Exact value of a is: 100