leafo / moonscript

:crescent_moon: A language that compiles to Lua
https://moonscript.org
3.23k stars 191 forks source link

Destructuring in function parameters #424

Open qtnc opened 4 years ago

qtnc commented 4 years ago

Hello,

I have just discovered moonscript, and it's quite a good language, thank you !

I don't know if this is a bug or a feature request, but if it isn't yet implemented, I think it would be interesting to be able to use destructuring in function parameters, too.

This moonscript:

f = ({ :a, :b, :c }) -> a+b+c

Is transcoded in lua into:

local f = ({
  a = a,
  b = b,
  c = c
})(function()
  return a + b + c
end)

Resulting in an obvious error in attempting to call a table.

The objective is to make a function with named parameters, as in:

print(f(a: 1, b: 2, c: 3)) -- prints "6"

IN order for that to work, the transcoded lua should look like this instead: local f f = function (t) if t is nil then t={} end local a, b, c = t.a, t.b, t.c return a+b+c end

AS a bonus, it would also be great to allow destructuring defaults. For example:

f = ({ :a = 1, :b = 2, :c = 3 }) -> a+b+c
print(f(a: 5, b: 4)) -- prints "12"

Second mini-bonus, what about removing parens if there's only a single parameter ? Like this:

f = { :a = 1, :b = 2, :c = 3 } -> a+b+c

This would allow to write more natural functional code also in some other contexts, like this, too:

table.removeIf = ...
t = { 1, 2, 3, 4, 5, 6, 7 }
table.removeIf(t, a -> a%2==1 )

Thank you very much !