Lua if語句

if語句由一個布爾運算式後跟一個或多個語句組成。

語法

Lua編程語言中if語句的語法是 -

if(boolean_expression)
then
   --[ statement(s) will execute if the boolean expression is true --]
end

如果布爾運算式的計算結果為true,那麼將執行if語句中的代碼塊。 如果布爾運算式的計算結果為false,則將執行if語句結束後(在結束大括弧之後)的第一組代碼。

Lua編程語言假定布爾truenon-nil值的任意組合為true,如果它是布爾falsenil,則假定為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

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