詳解Lua中if ... else語句的使用方法

來源:互聯網
上載者:User

詳解Lua中if ... else語句的使用方法

   這篇文章主要介紹了詳解Lua中if ... else語句的使用方法,是Lua入門學習中的基礎知識,需要的朋友可以參考下

  if 語句後面可以跟一個可選的else語句,當布林運算式為假該語句執行。

  文法

  在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和非零值的任意組合作為true,以及它是否是布爾假或零,則假定為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 ,但必須在elseif之前。

  if 之後可以有零到很多else if在else之前。

  一旦一個else if成功,其它的elseif將不會被測試。

  文法

  if...else if...else...else語句在Lua程式設計語言的文法是:

  代碼如下:

  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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.