邏輯運算子

在 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