邏輯運算符
and or not
邏輯運算符認為false和nil是假(false),其他為真,0也是true.
and和or的運算結果不是true和false,而是和它的兩個操作數相關。
a and b -- 如果a為false,則返回a,否則返回b
a or b -- 如果a為true,則返回a,否則返回b
例如:
print(4 and 5) --> 5
print(nil and 13) --> nil
print(false and 13) --> false
print(4 or 5) --> 4
print(false or 5) --> 5
一個很實用的技巧:如果x為false或者nil則給x賦初始值v
x = x or v
等價於
if not x then
x= v
end
and的優先級比or高。
C語言中的三元運算符
a ? b : c
在Lua中可以這樣實現:
(a and b) or c
not的結果只返回false或者true
print(not nil) --> true
print(not false) --> true
print(not 0) --> false
print(not not nil) --> false