6

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)

Goran Jovic
  • 9,418
  • 3
  • 43
  • 75

1 Answers1

12

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
Arthur Ulfeldt
  • 90,827
  • 27
  • 201
  • 284