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

如果布林表示式的計算結果為true,那麼將執行if程式碼塊,否則將執行else中的程式碼塊。

Lua程式設計語言假定布林truenon-nil值的任意組合為true,如果它是布林falsenil,則假定為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語句測試各種條件非常有用。

使用ifelse ifelse語句時,需要記住幾點 -

  • 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