clojure - eval code in different namespace

后端 未结 4 2152
情深已故
情深已故 2021-02-08 17:28

I\'m coding something like REPL Server. Request from users evaluates in such function:

(defn execute [request]
  (str (try
          (eval (read-string request))         


        
4条回答
  •  广开言路
    2021-02-08 18:25

    Changing namespace means that you will have to reinitialize all the aliases, or refer to even clojure.core stuff with a fully qualified name:

    user=> (defn alien-eval [ns str]
             (let [cur *ns*]
               (try ; needed to prevent failures in the eval code from skipping ns rollback
                 (in-ns ns)   
                 (eval (read-string str))
                 (finally 
                   (in-ns (ns-name cur))
                   (remove-ns ns))))) ; cleanup, skip if you reuse the alien ns
    #'user/alien-eval
    user=> (alien-eval 'alien "(clojure.core/println clojure.core/*ns*)") ; note the FQN
    # ; the effect of println
    nil                ; the return value of alien-eval
    

提交回复
热议问题