Internal conditions in Lua (a == b? "Yes": "no")?

Is there a way to use the built-in conditions in Lua?

For example:

print("blah: " .. (a == true ? "blah" : "nahblah")) 
+69
ternary lua conditional
Apr 2 2018-11-11T00:
source share
4 answers

Sure:

 print("blah: " .. (a and "blah" or "nahblah")) 
+94
Apr 02 2018-11-11T00:
source share

If a and t or f does not 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 a rollback that T and F are always evaluated .... to get around this, you need to provide the functions of your triple function, and this can become cumbersome:

 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)) 
+21
Apr 03 2018-11-11T00:
source share

There is a good article on the lua-users wiki about the ternary operator, as well as a description of the problem and several solutions.

+7
May 03 '13 at 5:42
source share

You can use ternary by declaring this next function -

 function if_(c, a, b) if c == true then return a else return b end end local a = 1, b = 1 --now just use the function like this print("blah " .. if_(a==b, "yes", "no")) 

You can follow read this for more information.

+1
Jul 07 '19 at 12:55 on
source share



All Articles