无论如何在Lua中使用内联条件?
如:
print("blah: " .. (a == true ? "blah" : "nahblah"))
答案 0 :(得分:94)
不确定
print("blah: " .. (a and "blah" or "nahblah"))
答案 1 :(得分:21)
如果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))
答案 2 :(得分:1)
虽然这个问题相当古老,但我认为建议另一种在语法上与三元运算符非常相似的替代方案是公平的。
添加:
function register(...)
local args = {...}
for i = 1, select('#', ...) do
debug.setmetatable(args[i], {
__call = function(condition, valueOnTrue, valueOnFalse)
if condition then
return valueOnTrue
else
return valueOnFalse
end
end
})
end
end
-- Register the required types (nil, boolean, number, string)
register(nil, true, 0, '')
然后像这样使用它:
print((true) (false, true)) -- Prints 'false'
print((false) (false, true)) -- Prints 'true'
print((nil) (true, false)) -- Prints 'false'
print((0) (true, false)) -- Prints 'true'
print(('') (true, false)) -- Prints 'true'
注意: 但是对于表格,您不能通过上述方法直接使用它们。这是因为每个表都有自己独立的元表,而 Lua 不允许您一次修改所有表。
在我们的例子中,一个简单的解决方案是使用 not not
技巧将表转换为布尔值:
print((not not {}) (true, false)) -- Prints 'true'