Skip to content
evandro92 edited this page Jun 12, 2015 · 7 revisions

Although people might think that a modern language needs try/catch, the usual Lua pcall idiom is not as clumsy in MoonScript, especially if we specialize it for the case where the function return value is not important.

For example,

try = (f) ->
    ok,err = pcall f
    if not ok then err\gsub '^[^:]+:%d+: ',''

err = try ->
    print a.x
if err
    print 'error!',err

--~ error!  attempt to index global 'a' (a nil value)

An even more suggestive syntax can constructed, thanks to SelectricSimian:

try
    do: ->
        print a.x
    catch: (e) ->
        print 'error!',e
    finally: ->
        print 'gets here'

We are exploiting the fact that Moonscript allows a table with only key-value pairs to be specified without curly braces. The definition of try is very simple:

try = (t) ->
    ok,err = pcall t["do"]
    if not ok
        t.catch err
    t.finally! if t.finally

Clone this wiki locally