详解Lua中if ... else语句的使用方法
if语句后面可以跟一个可选的else语句,当布尔表达式为假该语句执行。
语法
在Lua编程语言中的if...else语句的语法是:
if(boolean_expression) then --[statement(s)willexecuteifthebooleanexpressionistrue--] else --[statement(s)willexecuteifthebooleanexpressionisfalse--] end
如果布尔表达式的值为true,那么if代码块将被执行,否则else代码块将被执行。
Lua程序设计语言假定布尔true和非零值的任意组合作为true,以及它是否是布尔假或零,则假定为false值。但应当注意的是,在Lua零值被视为true。
例如:
--[localvariabledefinition--]
a=100;
--[checkthebooleancondition--]
if(a<20)
then
--[ifconditionistruethenprintthefollowing--]
print("aislessthan20")
else
--[ifconditionisfalsethenprintthefollowing--]
print("aisnotlessthan20")
end
print("valueofais:",a)
当建立和运行上面的代码,它会产生以下结果。
aisnotlessthan20 valueofais: 100
if...elseif...else语句
if语句后面可以跟一个可选的elseif...else语句,这是非常有用的使用,以测试各种条件单个if...elseif语句。
当使用if,elseif,else语句有几点要记住使用:
- if可以有零或一个else,但必须在elseif之前。
- if之后可以有零到很多elseif在else之前。
- 一旦一个elseif成功,其它的elseif将不会被测试。
语法
if...elseif...else...else语句在Lua编程语言的语法是:
if(boolean_expression1) then --[Executeswhenthebooleanexpression1istrue--]
elseif(boolean_expression2) --[Executeswhenthebooleanexpression2istrue--]
elseif(boolean_expression3) --[Executeswhenthebooleanexpression3istrue--] else --[executeswhenthenoneoftheaboveconditionistrue--] end
热门推荐
10 新娘生孩子祝福语简短
11 买车新年祝福语简短创意
12 66红包祝福语简短的
13 节日结束祝福语简短的
14 孩子过生日简短祝福语
15 体育校庆祝福语简短
16 清新唯美生日祝福语简短
17 立春祝福语简短微信
18 立春幽默祝福语简短