From 1a6eb52f11e8236dc700b7475a7925036ec5d3c1 Mon Sep 17 00:00:00 2001 From: Calvin Rose Date: Mon, 9 Dec 2019 17:32:02 -0600 Subject: [PATCH] Add protect macro. A more functional version of try catch. --- src/boot/boot.janet | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/boot/boot.janet b/src/boot/boot.janet index c11bcac8..e2932093 100644 --- a/src/boot/boot.janet +++ b/src/boot/boot.janet @@ -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."