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
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 may be
nil to short-circuit the expression to
t.?x on the other hand would short-circuit to
nil (this is not really necessary though since
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? 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
(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?