处理lua时,区分布尔值true和false和评估为true或false的值很重要。
lua中只有两个值的计算结果为false:nil和false,而其他所有值(包括数值)都0计算为true。
这意味着什么的一些示例:
if 0 then print("0 is true") end --> this will print "true" if (2 == 3) then print("true") else print("false") end --> this prints "false" if (2 == 3) == false then print("true") end --> this prints "true" if (2 == 3) == nil then else print("false") end --> prints false, because even if nil and false both evaluate to false, --> they are still different things.
lua中的逻辑运算符不一定会返回布尔值:
and 如果第一个值的计算结果为true,则将返回第二个值;
or 如果第一个值的计算结果为false,则返回第二个值;
就像其他语言一样,这使得模拟三元运算符成为可能:
local var = false and 20 or 30 --> returns 30 local var = true and 20 or 30 --> returns 20 -- in C: false ? 20 : 30
如果表不存在,也可以用来初始化表
tab = tab or {} -- if tab already exists, nothing happens
或避免使用if语句,使代码更易于阅读
print(debug and "there has been an error") -- prints "false" line if debug is false debug and print("there has been an error") -- does nothing if debug is false -- as you can see, the second way is preferable, because it does not output -- anything if the condition is not met, but it is still possible. -- also, note that the second expression returns false if debug is false, -- and whatever print() returns if debug is true (in this case, print returns nil)
由于不存在的变量返回nil,其结果为false,因此还可以轻松检查变量是否存在(如果已定义)。
local tab_1, tab_2 = {} if tab_1 then print("table 1 exists") end --> prints "table 1 exists" if tab_2 then print("table 2 exists") end --> prints nothing
唯一不适用此方法的情况是变量存储值时false,在这种情况下,该值在技术上是存在的,但仍评估为false。因此,创建返回false并nil取决于状态或输入的函数是一个糟糕的设计。我们仍然可以检查是否有anil或a false:
if nil == nil then print("A nil is present") else print("A nil is not present") end if false == nil then print("A nil is present") else print("A nil is not present") end -- The output of these calls are: -- A nil is present! -- A nil is not present