I can load arbitrary Clojure source using:
(load-string source)
However, if namespace wasn't provided, it loads code to clojure.core
namespace.
For example, following code:
(load-string "(defn add [a b] (+ a b))")
defines a function:
#'clojure.core/add
Now, is there a way to load that code to some other namespace, preferably the same one in which load-string
function is called?
(Other than prepending a namespace declaration to source
string before evaluation. I know that it would solve the problem - I'd like to know is there a preferred way)
when def
needs to decide what namspace a new function should go in it looks at the the current value of the ns
var and adds the new function to that namespace. because ns
is a var you can dynamically bind it before you call load-string
user> (binding [*ns* (find-ns 'foo)] (load-string "(defn f [] 4)"))
#'foo/f
user> (foo/f)
4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With