leafo / moonscript

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

wish moon could support: function?() #151

Open yi opened 10 years ago

yi commented 10 years ago

We use a lot of callbacks in moonscript. There is a very handy way in coffeescript to check if a callback exists:

for example:

callback? "Hello CoffeeScript!"

will generate:

if (typeof callback === "function") {
  callback("Hello CoffeeScript!");
}

I really wish we can have a similar thing in moonscript.

thanks

nefftd commented 10 years ago

This seems like a really specific use case, and can already be handled by this idiom:

callback! if callback
-- or
callback "argument" if type(callback) == 'function'
leafo commented 10 years ago

I like the idea of the ? operator, I use it a lot when I write coffeescript. Implementing it is part of a larger project to decompose expressions into a series of statements though, which is something I haven't had a chance to work on yet.

Idyllei commented 9 years ago

In lieu of using the ? operator for only functions/methods, why not make it like an inverse null-coallescing operator? Instead of calling a function if it exists, it would be nice if it checked to make sure the current value is not nil before continuing, otherwise returning nil. Ex:

tree = Tree!
leaf = tree?.branch[1]?.leaf

turns into

tree = Tree!
leaf = if tree
    if tree.branch[1]
        tree.branch[1].leaf

OR

tree = Tree()
leaf = if tree then if tree.branch[1] then return tree.branch[1].leaf

which in turn in Lua is:

local tree
tree = Tree()
local leaf
do
    if tree then
        if tree.branch[1] then
            leaf = tree.branch[1].leaf
        end
    end
end

We don't need to check if tree.branch[1].leaf is nil or not because if it is then wit would remain uninitialized (nil) anyway.

RyanSquared commented 8 years ago

Also, I feel like this could then be shortened when evaluating a statement that could then compile to:

local tree
tree = Tree()
local leaf
do
    if tree and tree.branch[1] then
        leaf = tree.branch[1].leaf
    end
end