使用和或邏輯運算子模擬三元運算子
在 lua 中,邏輯運算子 and
和 or
返回一個運算元作為結果而不是布林結果。因此,儘管 lua 在語言中沒有真正的三元運算子,但可以利用這種機制來模擬三元運算子的行為。
句法
condition 和 truthy_expr 或 falsey_expr
用於變數賦值/初始化
local drink = (fruit == "apple") and "apple juice" or "water"
在表建構函式中使用
local menu =
{
meal = vegan and "carrot" or "steak",
drink = vegan and "tea" or "chicken soup"
}
用作函式引數
print(age > 18 and "beer" or "fruit punch")
在 return 語句中使用
function get_gradestring(student)
return student.grade > 60 and "pass" or "fail"
end
警告
在某些情況下,此機制不具有所需的行為。考慮這種情況
local var = true and false or "should not happen"
在真正的三元運算子中,var
的期望值是 false
。然而,在 lua 中,and
評估’落後’,因為第二個運算元是假的。結果 var
最終以 should not happen
結束。
這個問題的兩種可能的解決方法,重構這個表示式,使中間運算元不是假的。例如。
local var = not true and "should not happen" or false
或者,使用經典的 if
then
else
構造。