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
如果布爾運算式的計算結果為true,那麼將執行if代碼塊,否則將執行else中的代碼塊。
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 if,else語句時,需要記住幾點 -
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
