Lua if...else statement
if...else statement
Lua if statement can be used together with the else statement. When the if condition expression is false, the code block of the else statement is executed.
The syntax format of the Lua if...else statement is as follows:
if(布尔表达式) then --[ 布尔表达式为 true 时执行该语句块 --] else --[ 布尔表达式为 false 时执行该语句块 --] end
When the boolean expression is true, the code block inside the if is executed; when the boolean expression is false, the code block of else is executed.
Lua considers false and nil to be false, and true and non-nil to be true. Note that in Lua, 0 is true.
The if statement flowchart is as follows:
Example
The following example is used to determine the value of variable a:
Example
a = 100;
--[ Check condition --]
if( a < 20 )
then
--[ Execute this statement block when the if condition is true --]
print("a is less than 20" )
else
--[ Execute this statement block when the if condition is false --]
print("a is greater than 20" )
end
print("The value of a is:", a)
The execution result of the above code is as follows:
a 大于 20 a 的值为 : 100
if...elseif...else statement
Lua if statement can be used together with the elseif...else statement. When the if condition expression is false, the elseif...else statement code block is executed to test multiple condition statements.
The syntax format of the Lua if...elseif...else statement is as follows:
if( 布尔表达式 1) then --[ 在布尔表达式 1 为 true 时执行该语句块 --] elseif( 布尔表达式 2) then --[ 在布尔表达式 2 为 true 时执行该语句块 --] elseif( 布尔表达式 3) then --[ 在布尔表达式 3 为 true 时执行该语句块 --] else --[ 如果以上布尔表达式都不为 true 则执行该语句块 --] end
Example
The following example evaluates the value of variable a:
Example
a = 100
--[ Check boolean condition --]
if( a == 10 )
then
--[ If the condition is true, print the following information --]
print("The value of a is 10" )
elseif( a == 20 )
then
--[ Print the following information when the if else-if condition is true --]
print("The value of a is 20" )
elseif( a == 30 )
then
--[ Print the following information when the if else-if condition is true --]
print("The value of a is 30" )
else
--[ Print the following information when none of the above condition statements is true --]
print("No value matches a" )
end
print("The real value of a is:", a )
The execution result of the above code is as follows:
没有匹配 a 的值 a 的真实值为: 100Other Extensions
Lua Control Flow