萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Lua 邏輯運算子 and / or / not 詳解與短路求值特性

Lua 的邏輯運算子 and、or、not 同樣採用短路求值,且返回運算元本身而非布林值,這與 Python 行為一致。

真值表(假設 a=true, b=false)

運算式結果說明
a and bfalseand 遇假回傳假值
a or btrueor 遇真回傳真值
not afalse取反
not btrue取反

實際程式碼範例

a, b = 5, 20
if a and b then print("Line 1 - true") end        -- 5 and 20 -> 20 (真)
if a or b then print("Line 2 - true") end         -- 5 or 20 -> 5 (真)

a, b = 0, 10
if a and b then print("Line 3 - true")            -- 0 and 10 -> 10 (真!Lua 中 0 為真)
else print("Line 3 - false") end
if not (a and b) then print("Line 4 - true")      -- not 10 -> false
else print("Line 4 - false") end

輸出結果

Line 1 - true
Line 2 - true
Line 3 - true
Line 4 - false

核心規則

  • 只有 false 和 nil 為假,數值 0、空字串 ""、空表 {} 皆為真。
  • x and y:若 x 為假返回 x,否則返回 y。
  • x or y:若 x 為真返回 x,否則返回 y。
  • 常見慣用語:x = x or default_value 設定預設值。
copyright © 萬盛學電腦網 all rights reserved