3 ms·
Lua basically already has ternary operators anyway since "and" and "or" short circuit. I also don't see the need of adding additional syntax for it. local x
by 201984 3mo ago
Lua basically already has ternary operators anyway since "and" and "or" short circuit. I also don't see the need of adding additional syntax for it.
local x = condition ? value_a : value b
local x = condition and value_a or value_b
- matheusmoreira 3mo ago> The classic Lua idiom a and b or c has a pitfall when b is nil or false: then c is returned, even when a is truthy. > E.g. true and false or 42 returns 42, whereas true ? false : 42 returns the (expected) false.
- deleted 3mo ago[deleted]
- nmz 3mo agoNo, not basically, it simply doesn't have them, Ternary means three as in it operates on 3 operands, and/or operates on 2 operands. They are also not equivalent. x = a ? b : c # x is b, same as you would if a {x=b} else {x=c} lua and/or a,b,c = true, 1, 2 x = a and b or c -- x is b a,b,c = true, false, 2 x = a and b or c -- x is c The or is dependent on its previous operand, so b will return false and skips to c, even if you meant for it to be b. you must use an if then else. However, you can have more than a ternary, if there is no need for short-circuit evaluation, as in, any of the operand is not a function CALL like c(), and you want to remain inside an expression, then you can do this instead select (select is a native C function, this is faster than the table creation below) x = select(a and 1 or 2, b, c) table creation/selection x = ({false,2})[a and 1 or 2] of course, doing something like local x; if a then x=b else x=c end does not look so bad