逻辑运算符

在 Lua 中,布尔值可以通过逻辑运算符来操作。这些运算符包括 notandor

在简单的表达式中,结果非常简单:

print(not true) --> false
print(not false) --> true
print(true or false) --> true
print(false and true) --> false

优先顺序

优先顺序类似于数学运算符 unary -*+

  • not
  • 然后 and
  • 然后 or

这可能导致复杂的表达:

print(true and false or not false and not true)
print( (true and false) or ((not false) and (not true)) )
    --> these are equivalent, and both evaluate to false

捷径评估

运算符 andor 可能只能使用第一个操作数进行评估,前提是第二个操作数是不必要的:

function a()
    print("a() was called")
    return true
end

function b()
    print("b() was called")
    return false
end

print(a() or b())
    --> a() was called
    --> true
    --  nothing else
print(b() and a())
    --> b() was called
    --> false
    --  nothing else
print(a() and b())
    --> a() was called
    --> b() was called
    --> false

惯用条件运算符

由于逻辑运算符的优先级,快捷评估的能力以及非 false 和非 nil 值的评估为 true,Lua 中提供了一个惯用的条件运算符:

function a()
    print("a() was called")
    return false
end
function b()
    print("b() was called")
    return true
end
function c()
    print("c() was called")
    return 7
end

print(a() and b() or c())
    --> a() was called
    --> c() was called
    --> 7
    
print(b() and c() or a())
    --> b() was called
    --> c() was called
    --> 7

此外,由于 x and a or b 结构的性质,如果 a 的评估结果为 false 将永远不会被返回,无论这个条件是什么,这条件总是会返回 b

print(true and false or 1)  -- outputs 1