An If statement can be followed by an optional else statement, when the Boolean expression is executed with a false statement.
Grammar
The syntax for the IF ... else statement in the LUA programming language is:
Copy Code code as follows:
if (boolean_expression)
Then
--[statement (s) would execute if the Boolean expression is true--]
Else
--[statement (s) 'll execute if the Boolean expression is false--]
End
If the Boolean expression evaluates to True, then the if code block will be executed, otherwise else code blocks will be executed.
The LUA programming language assumes a value of false if any combination of Boolean true and non-0 values is true and whether it is Boolean false or 0. It should be noted, however, that the LUA 0 value is considered true.
For example:
Copy Code code as follows:
--[local variable definition--]
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 produces the following results.
Copy Code code as follows:
A is not less than 20
Value of a is:100
If...else If...else Statement
An If statement can be followed by an optional else if ... else statement, which is useful to test various conditions for a single if...else if statement.
When using if, else if, the else statement has a few points to remember to use:
- If there can be 0 or one else, it must be preceded by a elseif.
- There can be 0 to many else if after else if.
- Once an else if succeeds, the other elseif will not be tested.
Grammar
The syntax for If...else if...else...else statements in the LUA programming language is:
Copy Code code as follows:
if (Boolean_expression 1)
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:
Copy Code code as follows:
--[local variable definition--]
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 produces the following results.
Copy Code code as follows:
None of the values is matching
Exact value of a is:100