# Lua if...else語句

2019-10-16 23:12:31

`if`語句後面可以跟一個可選的`else`語句，該語句在布林表示式為`false`時執行。

## 語法

Lua程式設計語言中`if...else`語句的語法是 -

``````if(boolean_expression)
then
--[ statement(s) will execute if the boolean expression is true --]
else
--[ statement(s) will execute if the boolean expression is false --]
end
``````

Lua程式設計語言假定布林`true``non-nil`值的任意組合為`true`，如果它是布林`false``nil`，則假定為`false`值。 需要注意的是，在Lua中，零將被視為`true`

``````--[ 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)
``````

``````a is not less than 20
value of a is :    100
``````

## if…else if…else語句

`if`語句後面可以跟一個`else if...else`語句，這對於使用單個`if...else if`語句測試各種條件非常有用。

• `if`語句有零個或一個`else`語句，它必須在`else if`語句之後。
• `if`語句有零或多個`else if`語句，並且它們必須在`else`語句之前。
• 當有一個`if else`匹配成功，其餘的其他`if`或者`if else`都不會再測試。

Lua程式設計語言中`if ... else if`語句的語法是 -

``````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
``````

``````--[ 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 )
``````

``````None of the values is matching
Exact value of a is:    100
``````