在Lua中的内联条件(a == b ? "yes" : "no")是什么意思?

有没有办法在 Lua 中使用内联条件?

比如:

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

原文链接 https://stackoverflow.com/questions/5525817

点赞
stackoverflow用户4323
stackoverflow用户4323
打印("blah: " .. (a and "blah" or "nahblah"))
2011-04-02 20:59:39
stackoverflow用户282536
stackoverflow用户282536

如果 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))
2011-04-03 12:29:48
stackoverflow用户8423261
stackoverflow用户8423261

虽然这个问题很老了,但我认为还是可以提供另一种语法上看起来很像三目运算符的替代方法。

添加以下代码:

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

-- 注册所需的类型(nil、boolean、number、string)
register(nil, true, 0, '')

然后像这样使用:

print((true)  (false, true)) -- 打印 'false'
print((false) (false, true)) -- 打印 'true'
print((nil)   (true, false)) -- 打印 'false'
print((0)     (true, false)) -- 打印 'true'
print(('')    (true, false)) -- 打印 'true'

注意: 对于表,您不能直接使用上述方法。这是因为每个表都有自己独立的元表,并且 Lua 不允许你一次修改所有表。

在我们的情况下,一个简单的解决方案是使用 not not 技巧将表转换为布尔值:

print((not not {}) (true, false)) -- 打印 'true'
2021-04-01 10:01:50
stackoverflow用户6427987
stackoverflow用户6427987
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 中,local 表示一个局部变量。以上代码中定义了一个局部变量 n 并将其赋值为 12。

do ... end 中定义了一个作用域,其中使用了一个匿名局部变量 x,该变量根据 n 的值输出相应的内容。

x 的赋值语句中使用了 andor 连接,这种写法通常称为 Lua 中的“短路写法”。它的执行顺序是从左到右,遇到第一个为 falsenil 的表达式则直接返回该值,否则返回最后一个表达式的值。

因此,以上代码中的 x 赋值语句执行完后,x 的值为 nil,因为 n 的值为 12,不符合任何条件。

2022-02-03 10:17:57
stackoverflow用户10401934
stackoverflow用户10401934

你可以将 if 语句写在一行中,这不是类似于缩写、内联或三元运算符的东西。

if (dummy) then
    print("dummy 是真的")
end

与下面的代码是相等的

if (dummy) then print("dummy 是真的") end
2022-03-09 20:52:05
stackoverflow用户15459779
stackoverflow用户15459779

你通常可以这样做:

condition and ifTrue or ifFalse

但这并不一定是最好的方法。主要原因是,如果ifTrue是一个假值(有时候),即使condition是一个真值,ifFalse也会被评估。一种简单而不需要太多额外工作的方法是:

(condition and {ifTrue} or {ifFalse})[1]

它不仅是一个表达式,而且不受ifTrue是假值的问题的约束,因此它可以处理所有情况,并且还具有短路(不评估另一个表达式)的优点。无需额外函数或混乱的Lua复杂方面。

2022-04-26 23:23:57