Lua中的内联条件(a == b?“是”:“否”)?


88

无论如何,在Lua中可以使用内联条件吗?

如:

print("blah: " .. (a == true ? "blah" : "nahblah"))

1
在lua-users Wiki上有一篇关于三元运算符的不错的文章,以及问题的解释和几种解决方案。
— Marcin

Answers:


120

当然:

print("blah: " .. (a and "blah" or "nahblah"))

31
+1作为答案。但是,我不认为这是完全正确的-我不使用LUA-但我认为这种方法与其他语言的三元运算符有共同的“缺陷”。想象:在所有情况下(cond and false-value or x)都会导致x。

1
那样也不会打印出A的值吗?
— corsiKa 2011年

11
@glowcoder否。“如果此值是false或nil,则合取运算符(和)返回其第一个参数;否则,返回其第二个参数。如果此值不同于nil和false,则合取运算符(或)返回其第一个参数;和或使用快捷方式评估,即仅在必要时评估第二个操作数。“-from lua.org/manual/5.0/manual.html

3
@pst是正确的,如果意图是a and false or true不会给出与相同的答案not a。此惯用法通常用于期望值if atrue不能为false或的情况nil。
— RBerteig

1
如果您将此表单与变量一起使用,则可能会假设第二个变量为非false,这意味着您应该编写a and assert(b) or c。
— HoverHell

29

如果a and t or f不适用于您,则始终可以创建一个函数:

function ternary ( cond , T , F )
    if cond then return T else return F end
end

print("blah: " .. ternary(a == true ,"blah" ,"nahblah"))

当然,您有一个缺点,那就是总是要对T和F进行求值..为了避免这种情况,您需要为三元函数提供函数,而这可能很笨拙:

function ternary ( cond , T , F , ...)
    if cond then return T(...) else return F(...) end
end

print("blah: " .. ternary(a == true ,function() return "blah" end ,function() return "nahblah" end))

我认为这对于布尔变量最有用
— Vyacheslav

这个答案实际上比最高答案更好,因为它也适用于布尔值。
— ДеянДобромиров

我认为此解决方案可容纳的更常见的情况是when tis nil。
— NetherGranite
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.