Lua巢狀if語句

2019-10-16 23:12:33

在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