Lua嵌套if語句

在Lua編程中嵌套if-else語句是合法的,這意味著在一個ifelse if語句中可以使用另一個ifelse if語句。

語法

嵌套if語句的語法如下 -

if( boolean_expression 1)
then
   --[ Executes when the boolean expression 1 is true --]
   if(boolean_expression 2)
   then
      --[ Executes when the boolean expression 2 is true --]
   end
end

使用與嵌套if語句類似的方式嵌套if else語句。

示例

--[ local variable definition --]
a = 100;
b = 200;

--[ check the boolean condition --]

if( a == 100 )
then
   --[ if condition is true then check the following --]
   if( b == 200 )
   then
      --[ if condition is true then print the following --]
      print("Value of a is 100 and b is 200" );
   end
end

print("Exact value of a is :", a );
print("Exact value of b is :", b );

構建並運行上面的代碼時,會產生以下結果 -

Value of a is 100 and b is 200
Exact value of a is :    100
Exact value of b is :    200

上一篇: Lua決策結構 下一篇: Lua函數