Inline conditions in Lua (a == b ? "yes" : "no")?

LuaConditionalTernary

Lua Problem Overview


Is there anyway to use inline conditions in Lua?

Such as:

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

Lua Solutions


Solution 1 - Lua

Sure:

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

Solution 2 - Lua

If the a and t or f doesn't work for you, you can always just create a function:

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

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

of course, then you have the draw back that T and F are always evaluated.... to get around that you need to provide functions to your ternary function, and that can get unwieldy:

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))

Solution 3 - Lua

Although this question is fairly very old, I thought it would be fair to suggest another alternative that syntactically appears very similar to that of the ternary operator.

Add this:

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, '')

And then use it like this:

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'


> Note: For tables, however, you cannot use them directly with the above method. This is because each and every table has it's own independent metatable and Lua does not allow you to modify all tables at once. > > In our case, an easy solution would be to convert the table into a boolean using the not not trick: > > lua > print((not not {}) (true, false)) -- Prints 'true' >

Solution 4 - Lua

Have fun :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

Solution 5 - Lua

You could just write the if statement in one line, it is no shorthand, inline or ternary operator stuff tho.

if (dummy == true) then
    print("dummy is true")
end

is equal too

if (dummy = true) then print("dummy is true") end

Solution 6 - Lua

You can usually do:

condition and ifTrue or ifFalse

but this isn't necessarily the best way to do it. The major reason why is because if ifTrue is a falsy value (some of the time), ifFalse will evaluate even if condition is a truthy value. One way to do it simply without much extra work is:

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

which has the advantage of not only being an expression and not being subject to the problem of ifTrue being falsy which means it can handle all cases, but also has the advantage of short-circuiting (not evaluating the other expression). No need for extra functions or messing with complex aspects of Lua.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSoftnuxView Question on Stackoverflow
Solution 1 - LuaJohn ZwinckView Answer on Stackoverflow
Solution 2 - LuadaurnimatorView Answer on Stackoverflow
Solution 3 - LuaRuksView Answer on Stackoverflow
Solution 4 - LuakaiuriView Answer on Stackoverflow
Solution 5 - LuaKonrniView Answer on Stackoverflow
Solution 6 - LuauknonotView Answer on Stackoverflow