Warning: Some posts on this platform may contain adult material intended for mature audiences only. Viewer discretion is advised. By clicking ‘Continue’, you confirm that you are 18 years or older and consent to viewing explicit content.
Yeah, I’ve always hated Python’s ternary, and I use it every day at work. Though you can do the same in Python if you want:
x = [condition] and [true value] or [false value]
I consider that bad style because the dedicated syntax is preferred. You can also do similar in JS:
x = [condition] && [true value] || [false value]
The caveat in both (and Lua) is that you’ll get the false value if the true value is falsey.
My favorite syntax is Rust:
x = if [condition] { [true value] } else { [false value] };
This preserves the flow you get with the ? :, allows [true value] to be falsey, and is idiomatic without having a lot of extra syntax.
My favorite thing about Lua is that tables separate numeric from string keys, so you can do this:
x = { metadata = ... }
x[1] = 3
x[2] = 4
print(#x) -- prints 2
This is really nice for representing something like an XML/HTML DOM, where numeric indices are child nodes, and string keys are attributes. Or you can store metadata about a list in the list itself (e.g. have a reference to the max value, min value, etc). It’s just really nice to work with.
Yeah, I’ve always hated Python’s ternary, and I use it every day at work. Though you can do the same in Python if you want:
I consider that bad style because the dedicated syntax is preferred. You can also do similar in JS:
The caveat in both (and Lua) is that you’ll get the false value if the true value is falsey.
My favorite syntax is Rust:
This preserves the flow you get with the
? :
, allows [true value] to be falsey, and is idiomatic without having a lot of extra syntax.My favorite thing about Lua is that tables separate numeric from string keys, so you can do this:
This is really nice for representing something like an XML/HTML DOM, where numeric indices are child nodes, and string keys are attributes. Or you can store metadata about a list in the list itself (e.g. have a reference to the max value, min value, etc). It’s just really nice to work with.
Haskell’s
if
is pretty nice:if cond then truthy else falsy