逻辑运算

基本类型 / 布尔类型

local value1 = true
local value2 = false

local value_not1 = not value1
-- value_not1 = false

local value_not2 = not value2
-- value_not2 = true

local value_and = value1 and value2
-- value_and = false

local value_or = value1 or value2
-- value_or = true

-- No xor operator: for booleans compare the two
local value_xor = value1 ~= value2
-- value_xor = true

-- and, or return one of the operands
local last_operand = 1 and 2
-- last_operand = 2

local with_default = nil or "found"
-- with_default = found

-- The right side is skipped when the left decides
local skipped = false and error("never run")
-- skipped = false

print("value_not1 = " .. tostring(value_not1))
print("value_not2 = " .. tostring(value_not2))
print("value_and = " .. tostring(value_and))
print("value_or = " .. tostring(value_or))
print("value_xor = " .. tostring(value_xor))
print("last_operand = " .. last_operand)
print("with_default = " .. with_default)
print("skipped = " .. tostring(skipped))

-- ~ between booleans is not xor, it is an error
local ok, err = pcall(function()
  return value1 ~ value2
end)
-- ok = false
-- err = main.lua:42: attempt to perform bitwise
-- operation on a boolean value (upvalue 'value1')
print("ok = " .. tostring(ok))
print("err = " .. err)