Idea: Null/nil coalescing operator: ?. and ?\
Currently, I often see stuff like this:
some_value\xyz! if some_value
var = if some_value then some_value.attr else nil
Many languages (C#, Dart, many others) now have a null coalescing operator. Adding that to MoonScript would turn the above code into:
some_value?\xyz!
var = some_value?.attr
(Of course, the ? could also be put after the symbol like some_value\?xyz and some_value.?attr, though I find that a lot harder to read.)
I think this would especially make a great addition since nil is such an important value in Lua.
Cound be useful.
That would be great ! I also think of ?? and ?=.
-- a = if b != nil then b else c
a = b ?? c
-- a = b if a == nil
a ?= b
Could also be useful to have anaphoric constructions if x then f that => local that; that = x; if that then f(that).
Would that not be achievable by f(x) if x ?
It's an issue if x has side effects.
Something I think would be neat instead would be:
x? |> f(_)
I feel like this, first off, fits with MoonScript's usage of _ as a placeholder variable (so that you can assign to the placeholder for the "check" portion) as well as being a shorter format, still using the ? syntax.
It would compile to something like:
a[b]? |> print("Hello, #{_}")
turns into
local _ = a[b]
if _ then
print("Hello, " .. _)
end
This could perhaps also be used as a "function call" selector, so that:
*a\b!? |> print(table.concat(_))
turns into
local _ = {a:b()}
if _[1] then
print(table.concat(_))
end
This would be useful, for example, with IO operations. Take note that ~ could be used to negate it.
*file\read!? ~|> print("File read error:", _[2])
local _ = {file:read()}
if not _[1] then
print("File read error:", _[2])
end
I really think that those should be two different things, tho I'm not opposed to a ?|> truthy pipe, or something like Elixir's with. See https://github.com/satyr/coco/issues/197.
I would love to see this feature added. Coming from the JVM world, it's one of the things I really miss from Kotlin.