Lua 中是否可以使用内联条件?
如:
print("blah: " .. (a == true ? "blah" : "nahblah"))
当然:
print("blah: " .. (a and "blah" or "nahblah"))
如果
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))
您通常可以这样做:
condition and ifTrue or ifFalse
但这不一定是最好的方法。主要原因是如果
ifTrue
是假值(有时),即使 ifFalse
是真值,condition
也会进行评估。无需太多额外工作即可简单完成此操作的一种方法是:
(condition and {ifTrue} or {ifFalse})[1]
它的优点是不仅是一个表达式并且不会受到
ifTrue
为假的问题的影响,这意味着它可以处理所有情况,而且还具有短路的优点(不评估其他情况)表达)。不需要额外的功能或弄乱 Lua 的复杂方面。
虽然这个问题相当古老,但我认为提出另一种在语法上与三元运算符非常相似的替代方案是公平的。
添加此:
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'
你可以将 if 语句写在一行中,它不是速记、内联或三元运算符之类的东西。
if (dummy) then
print("dummy is true")
end
也相等
if (dummy) then print("dummy is true") end
玩得开心 :D
local n = 12
do
local x = (n>15)
and print(">15")
or n>13
and print(">13")
or n>5
and print(">5")
end
Lua 故意做到轻量级,因此它没有三元运算符。
有几种方法可以解决这个问题,包括使用 and-or 习语。但我认为这很糟糕,原因有很多。主要是初学者不明白。
我建议使用一个函数:
local function choice(c, t, f)
return ({
[true] = t,
[false] = f
})[c]
end
local s = choice(2 % 2 == 0, "even", "odd")