1
0
mirror of https://github.com/janet-lang/janet synced 2024-11-28 11:09:54 +00:00

Add when-with and if-with

This is useful for reading from files.
This commit is contained in:
Calvin Rose 2020-01-15 22:49:41 -06:00
parent 65be9ae095
commit 962cd7e5f5
3 changed files with 31 additions and 0 deletions

View File

@ -17,6 +17,8 @@ All notable changes to this project will be documented in this file.
in libuv or embedded in a game.
- Add `defer`
- Add `assert`
- Add `when-with`
- Add `if-with`
- Fix thread module issue where sometimes decoding a message failed.
- Fix segfault regression when macros are called with bad arity.

View File

@ -304,6 +304,22 @@
(defer (,(or dtor :close) ,binding)
,;body)))
(defmacro when-with
"Similar to with, but if binding is false or nil, returns
nil without evaluating the body. Otherwise, the same as with."
[[binding ctor dtor] & body]
~(if-let [,binding ,ctor]
(defer (,(or dtor :close) ,binding)
,;body)))
(defmacro if-with
"Similar to with, but if binding is false or nil, returns
nil without evaluating the body. Otherwise, the same as with."
[[binding ctor dtor] truthy &opt falsey ]
~(if-let [,binding ,ctor]
(defer (,(or dtor :close) ,binding) ,truthy)
,falsey))
(defn- for-template
[binding start stop step comparison delta body]
(with-syms [i s]

View File

@ -286,4 +286,17 @@
(file/seek f :set 0)
(assert (= (string (file/read f :all)) "foo\n") "temp files work"))
(var counter 0)
(when-with [x nil |$]
(++ counter))
(when-with [x 10 |$]
(+= counter 10))
(assert (= 10 counter) "when-with 1")
(if-with [x nil |$] (++ counter) (+= counter 10))
(if-with [x true |$] (+= counter 20) (+= counter 30))
(assert (= 40 counter) "if-with 1")
(end-suite)