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