Many languages extend their "indexing" operator .
to a nil-coalescing variant ?.
to deal with indexing chains such as a.b.c
where the parents are optional, which can then be conveniently rewritten as a?.b?.c
. This seems to be the main use case for nil-coalescing besides providing a default if something is nil
, e.g. x ?? 42
(I'm using the Lua term nil
rather than null
here since I plan to extend Lua).
I'm considering generalizing this: All binary operators should support nil coalescion for both operands by putting a question mark on their respective sides. For example, you could write t?.x
if t
may be nil
to short-circuit the expression to nil
. t.?x
on the other hand would short-circuit to nil
if x
is nil
(this is not really necessary though since t[nil]
is nil
in Lua, given no metamethods).
This seems to be useful for arithmetic operations (e.g. c = a ?+? b
could come in handy) and I would prefer not to impose arbitrary restrictions on which operators nil-coalesce. Relational operators could also benefit.
It is however pretty useless if not detrimental for the logic operators not
, and
and or
: not? nil
would evaluate to nil
, which would be rather confusing, since we get a conflict between nil-coalescing operators short-circuiting and logic operators short-circuiting as well as conflicting behavior: nil ?or 1
would evaluate to nil
, behaving like and
rather than or
.
(In a Lua extension), should nil-coalescing be restricted to indexing (and the "default" operator ??
), where it is most useful? Which limits should be imposed on a generalization?
?.
referred to as optional-chaining, and only??
is coalescing. $\endgroup$[?]<op>[?]
operators are supposed to benil
-short-circuiting rather than "coalescing"... $\endgroup$