鍍金池/ 教程/ C/ Lua if...else語句
Lua邏輯運算符
Lua其他運算符
Lua協(xié)同程序
Lua break語句
Lua運算符
Lua面向?qū)ο?/span>
Lua教程
Lua函數(shù)
Lua數(shù)據(jù)庫/MySQL操作
Lua關(guān)系運算符
Lua錯誤處理
Lua數(shù)據(jù)類型
Lua嵌套循環(huán)
Lua變量
Lua基本語法
Lua字符串
Lua for循環(huán)
Lua if語句嵌套
Lua運算符優(yōu)先級
Lua Web編程
Lua while循環(huán)
Lua開發(fā)環(huán)境
Lua if...else語句
Lua標準庫
Lua游戲編程
Lua if語句
Lua算術(shù)運算符
Lua表格
Lua決策
Lua文件I/O
Lua循環(huán)
Lua數(shù)組
Lua元表
Lua repeat...until循環(huán)
Lua迭代器
Lua調(diào)試
Lua模塊
Lua垃圾收集

Lua if...else語句

if 語句后面可以跟一個可選的else語句,當布爾表達式為假該語句執(zhí)行。

語法

在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代碼塊將被執(zhí)行,否則else代碼塊將被執(zhí)行。

Lua程序設(shè)計語言假定布爾true和非零值的任意組合作為true,以及它是否是布爾假或零,則假定為false值。但應(yīng)當注意的是,在Lua零值被視為true。

流程圖:

Lua if...else statement

例如:

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

當建立和運行上面的代碼,它會產(chǎn)生以下結(jié)果。

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 )

當建立和運行上面的代碼,它會產(chǎn)生以下結(jié)果。

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

上一篇:Lua元表下一篇:Lua函數(shù)