moonscript icon indicating copy to clipboard operation
moonscript copied to clipboard

Idea: Null/nil coalescing operator: ?. and ?\

Open refi64 opened this issue 9 years ago • 8 comments

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.

refi64 avatar Aug 30 '16 20:08 refi64

Cound be useful.

buckle2000 avatar Dec 09 '16 11:12 buckle2000

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

Drestin avatar Jun 30 '17 19:06 Drestin

Could also be useful to have anaphoric constructions if x then f that => local that; that = x; if that then f(that).

vendethiel avatar Dec 14 '17 14:12 vendethiel

Would that not be achievable by f(x) if x ?

RyanSquared avatar Dec 14 '17 17:12 RyanSquared

It's an issue if x has side effects.

vendethiel avatar Dec 14 '17 17:12 vendethiel

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

RyanSquared avatar Dec 14 '17 18:12 RyanSquared

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.

vendethiel avatar Dec 14 '17 18:12 vendethiel

I would love to see this feature added. Coming from the JVM world, it's one of the things I really miss from Kotlin.

OmarAssadi avatar Apr 01 '18 12:04 OmarAssadi