if
語句由一個布林表示式後跟一個或多個語句組成。
Lua程式設計語言中if
語句的語法是 -
if(boolean_expression)
then
--[ statement(s) will execute if the boolean expression is true --]
end
如果布林表示式的計算結果為true
,那麼將執行if
語句中的程式碼塊。 如果布林表示式的計算結果為false
,則將執行if
語句結束後(在結束大括號之後)的第一組程式碼。
Lua程式設計語言假定布林true
和non-nil
值的任意組合為true
,如果它是布林false
或nil
,則假定為false
值。 需要注意的是,在Lua中,零將被視為true
。
流程圖
範例程式碼
--[ local variable definition --]
a = 10;
--[ check the boolean condition using if statement --]
if( a < 20 )
then
--[ if condition is true then print the following --]
print("a is less than 20" );
end
print("value of a is :", a);
構建並執行上面的程式碼時,會產生以下結果。
a is less than 20
value of a is : 10