Lua 逻辑运算符

示例

在Lua中,可以通过逻辑运算符来操作布尔值。这些运营商包括not,and,和or。

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

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


优先顺序

优先顺序类似于一元数学运算符-,*以及+:

  • 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


快捷评估

运算符,and并且or可能仅使用第一个操作数进行评估,前提是不需要第二个:

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


惯用条件运算符

由于逻辑运算符的优先级,因此可以在Lua中使用快捷条件评估和对as进行非false和非nil值评估的功能true:惯用条件运算符:

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无论是什么x是。

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