Runtime evaluation: Difference between revisions

Line 150:
 
There are no standardized debugging facilities specific to the <code>eval</code> operation itself, but code evaluted may be affected by the current [http://www.lispworks.com/documentation/HyperSpec/Body/03_c.htm global declarations], particularly the [http://www.lispworks.com/documentation/HyperSpec/Body/d_optimi.htm <code>optimize</code> declaration]'s <code>debug</code> and <code>safety</code> qualities.
 
=={{header|Common Lisp}}==
The <tt>eval</tt> function evaluates a form at runtime. The form can be Lisp code in a list. Here, I just quote a list. You can use any list operations to make a list.
 
<lang lisp>(eval '(format t "~%Rosetta Code"))
 
;; When the code is in a variable:
(let ((code '(format t "~%Rosetta Code")))
(eval code))
 
;; When the code is in a string:
(eval (read-from-string "(format t \"~%Rosetta Code\")"))</lang>
 
<tt>eval</tt> runs its argument in a ''null lexical environment''. This means that the code inside the <tt>eval</tt> cannot see lexical variables from outside the <tt>eval</tt>.
 
<lang lisp>(let ((x 11) (y 22))
;; This is an error! Inside the eval, x and y are unbound!
(format t "~%x + y = ~a" (eval '(+ x y))))</lang>
 
One way to fix the error is to use <tt>(declare (special x y))</tt> for dynamic variables; but the easier and shorter way is to insert the values of x and y into the code before calling <tt>eval</tt>.
 
<lang lisp>(let ((x 11) (y 22))
(format t "~%x + y = ~a" (eval `(+ ,x ,y))))</lang>
 
The above example evaluates <tt>(+ 11 22)</tt>, because the backquote inserted the values of x and y before <tt>eval</tt> got the code. <tt>eval</tt> passes the return value, so the code outputs <tt>x + y = 33</tt>.
 
=={{header|E}}==
Anonymous user