Lua中if ... else語句的詳解用法
if 語句後面可以跟一個可選的else語句,當布爾表達式爲假該語句執行。
語法
在Lua編程語言中的 ... 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 語句。
當使用if , else if , else語句有幾點要記住使用:
if 可以有零或一個 else ,但必須在elseif之前。
if 之後可以有零到很多else if在else之前。
一旦一個else if成功,其它的elseif將不會被測試。
語法
語句在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
-
給女朋友留言的暖心句子(精選190句)
無論在學習、工作或是生活中,大家都收藏過自己喜歡的句子吧,句子的組成部分,包括主語、謂語、賓語、定語、狀語、補語六種。那麼你有真正瞭解過句子嗎?以下是小編爲大家收集的給女朋友留言的暖心句子(精選190句),歡迎閱讀與收藏。1、還在上班嗎?你這段時間忙壞了吧。要...
-
愛情結束要放手的語句
當愛情結束時,就放手吧!糾纏,充其量只是延長暫時擁有的時間。唯有放手,被負的那一方,纔會有真正的自由。感情走到最後,如果一定要分手,就該灑脫,因爲,苦苦糾纏是不會有結果的。正如同相愛是兩個人的事,分手也該是雙方共同接受的決定。經過多次感情歷練的人,有朝一日一定...
-
簡單的早安共勉句子QQ65條
苦難是強者的墊腳石,磨難是懦夫的攔路虎。早安!以下是小編收集整理的早安共勉句子65條,感興趣的一起來看看吧。1、風,送來了秋天的第一枚葉子,旋在手心,在季節的輪迴裏飄飛。淡淡的暖陽悄悄告別夏的絢爛,奼紫嫣紅,輕輕挽出秋的素雅清麗,和着聲聲的鳥鳴。早安!2、真正的...
-
經典唯美的句子(精選470句)
無論是身處學校還是步入社會,大家總免不了要接觸或使用句子吧,在不同類型的文章裏,不同位置的句子的作用也是不同的。那麼什麼樣的句子纔是好的句子呢?下面是小編收集整理的經典唯美的句子,希望對大家有所幫助。1、相逢一醉是前緣,風雨散,飄然何處。2、落落晨星,斜雨竹...