clojure - eval code in different namespace

后端 未结 4 2153
情深已故
情深已故 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:16

    Solved:

    (binding [*ns* user-ns] (eval (read-string request)))
    
    0 讨论(0)
  • 2021-02-08 18:18

    You can write a macro that mimics

    (defmacro my-eval [s] `~(read-string s))
    

    It works better that eval because the symbol resolution of s occurs in the context that calls my-eval. Thanks to @Matthias Benkard for the clarifications.

    0 讨论(0)
  • 2021-02-08 18:22

    (symbol (str "client-" (Math/abs (.nextInt random)))

    I just wanted to add, that this could be achieved with

    (gensym "client-")
    

    (I wanted to comment, but it turns our that I can't :))

    0 讨论(0)
  • 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
    #<Namespace alien> ; the effect of println
    nil                ; the return value of alien-eval
    
    0 讨论(0)
提交回复
热议问题