Other practical example why ternary is bad: Many code-coverage solutions break on ternary because they don't correctly see that one of the branches was missed in tests.
if c
x=1
else
x=2
If I ever want to change x, or refactor this code some other way, its a more brittle process over x=c?1:2The ternary expression also takes up much less space so there is less of an emphasis on it, this can be a stylistic tool in a programmer's toolbox
Of course there are differences between LuaJIT and Luau that I think influence their decisions on possible ternary expression features:
- Luau users are disproportionately beginners to programming that I believe would find the if-then-else expression syntax easier to learn; LuaJIT developers have a larger user base of professional devs wanting to make their code faster, and they will probably be more familiar with the `x ? y : z` style since it's used in plenty of other languages.
- Luau is a lot faster moving in its development than LuaJIT in terms of language features, the Luau team just wanted to move people to ternaries from `x and y or z` because it's easier to optimise in a normal interpreter; LuaJIT, with their JIT, I assume would be able to more easily implement optimisations for constructs like `x and y or z` despite its slight semantic differences (my assumption on why the change is being considered now rather than earlier).
Does that operator compile to faster assembly that if I make the same logic with verbose `if` logic? Is that a language specific outcome?
cond1 ? res1 :
cond2 ? res2 :
cond3 ? res3 :
or_else_res
If they are truly nested, then that is confusing. But if you have an if-else chain, then it can be quite readable. (cond (cond1 res1)
(cond2 res2)
(cond3 res3)
(t else_res))
=) if cond1 then res1
else if cond2 then res2
else if cond3 then res3
else or_else_res
or if cond1 then res1
elif cond2 then res2
elif cond3 then res3
else or_else_res
what is most lua-like?The ? is basically an attempt to use fewer if/else, at the cost of condensed if-else like structure. I always need to look at both parts after the ? whereas in a single if or elsif I don't. case/when in ruby is even better here e. g. regex check:
def foo(i)
case i
when /^cat/
handle_cats
when /^dog/
handle_dogs
(I ommitted the "end"s here to just focus on the conditional logic.)