lua的逻辑运算符与传统的程序语言逻辑运算符的运算有点区别。在C语言中与、或、非的结果是布尔值,而在lua中逻辑运算的结果可以不为布尔值。
下表列出了 Lua 语言中的常用逻辑运算符,设定 A 的值为 true,B 的值为 false:
操作符 | 描述 | 实例 |
---|---|---|
and | 逻辑与操作符。 若 A 为 false,则返回 A,否则返回 B。 | (A and B) 为 false。 |
or | 逻辑或操作符。 若 A 为 true,则返回 A,否则返回 B。 | (A or B) 为 true。 |
not | 逻辑非操作符。与逻辑运算结果相反,如果条件为 true,逻辑非为 false。 | not(A and B) 为 true。 |
实例:
local a = true
local b = true
print("a = " .. tostring(a) .. " , " .. "b = " .. tostring(b))
print("a and b = " .. tostring(a and b) )
print("a or b = " .. tostring(a or b) )
print("not( a and b) = " .. tostring(not( a and b)))
a = false
b = true
print("a = " .. tostring(a) .. " , " .. "b = " .. tostring(b))
print("a and b = " .. tostring(a and b))
print("a or b = " .. tostring(a or b) )
print("not( a and b) = " .. tostring(not( a and b)))
以上程序执行结果为: