1
0
mirror of https://github.com/janet-lang/janet synced 2024-12-27 17:00:27 +00:00

Add protect macro.

A more functional version of try catch.
This commit is contained in:
Calvin Rose 2019-12-09 17:32:02 -06:00
parent 4c5734c2ee
commit 1a6eb52f11

View File

@ -218,11 +218,21 @@
f (gensym)
r (gensym)]
~(let [,f (,fiber/new (fn [] ,body) :ie)
,r (resume ,f)]
,r (,resume ,f)]
(if (= (,fiber/status ,f) :error)
(do (def ,err ,r) ,(if fib ~(def ,fib ,f)) ,;(tuple/slice catch 1))
,r))))
(defmacro protect
"Evaluate expressions, while capturing any errors. Evaluates to a tuple
of two elements. The first element is true if successful, false if an
error, and the second is the return value or error."
[& body]
(let [f (gensym) r (gensym)]
~(let [,f (,fiber/new (fn [] ,;body) :ie)
,r (,resume ,f)]
[(,not= :error (,fiber/status ,f)) ,r])))
(defmacro and
"Evaluates to the last argument if all preceding elements are true, otherwise
evaluates to false."