Lua if...else语句

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

上一篇: Lua决策结构 下一篇: Lua函数