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

时间:2011-04-02 20:56:49

标签: lua conditional ternary

无论如何在Lua中使用内联条件?

如:

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

3 个答案:

答案 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'