3 ms·
SBCL has EVAL-IN-FRAME, which, used in conjunction with FIND-CALLER-NAME-AND-FRAME, can be used to access variables by name at runtime. The variables may or may
by oalae5niMiel7qu 10y ago
SBCL has EVAL-IN-FRAME, which, used in conjunction with FIND-CALLER-NAME-AND-FRAME, can be used to access variables by name at runtime. The variables may or may not actually be there depending on the OPTIMIZE settings. SBCL removes unreferenced variables. Here's how to implement LEXICAL-EVAL, which evaluates its argument in the current lexical scope instead of in the toplevel environment:
(defpackage :lexical-eval
(:use :common-lisp :sb-kernel :sb-di))
(in-package :lexical-eval)
(defmacro second-value (form)
`(multiple-value-bind (a b)
,form
(declare (ignore a))
b))
(defun lexical-eval (form)
(eval-in-frame (second-value (find-caller-name-and-frame))
form))
Then you can do this:
(let ((x 2))
;; Prevent X from getting optimized out:
(setf *some-global-var* x)
(lexical-eval 'x))
In CLISP, there is EVAL-ENV and (THE-ENVIRONMENT), which can be used to accomplish the same thing.