Lisp HUG Maillist Archive

evaluating exoressions created from strings

Hello,
 
I am parsing code written for a C++ application into lisp code.
I run into a problem with binding of variables referenced in a string representation of the parsed code.
 
(let* ((x1 2) (x2 2) (s "(equal x1 x2)")
       (slist (read-from-string s)))
  (format t "~&slist: ~S" slist)
  (format t "~&(equal x1 x2): ~S" (equal x1 x2))
  (format t "~&(eval slist): ~S" (eval slist)))
 
slist: (EQUAL X1 X2)
(equal x1 x2): T
EDITOR::EVALUATION-ERROR
Error while evaluating: The variable X1 is unbound.
 
Any help is appreciated.
 
Thanks,
Sheldon

Re: evaluating exoressions created from strings

This happens because x1 and x2 are lexically bound in the let*, while
your (eval ...) is executed at a later time and in a different
context. You (probably) need to use dynamic (special) bindings
instead, which you could set up with (progv ...):

(progv '(x1 x2 s) '(2 2 "(equal x1 x2)")
  (let ((slist (read-from-string s)))
    (format t "~&slist: ~S" slist)
    (format t "~&(equal x1 x2): ~S" (equal x1 x2))
    (format t "~&(eval slist): ~S" (eval slist))))

Ref: http://www.lispworks.com/documentation/HyperSpec/Body/s_progv.htm#progv

Alternatively, you could move the (let* ...) inside the string you are
evaluating, but that would mean that you have to generate a new string
each time you want to evaluate for a new set of values.

On Thu, Sep 23, 2010 at 6:01 AM, Sheldon Ball <sheldon.ball@gmail.com> wrote:
> Hello,
>
> I am parsing code written for a C++ application into lisp code.
> I run into a problem with binding of variables referenced in a string
> representation of the parsed code.
>
> (let* ((x1 2) (x2 2) (s "(equal x1 x2)")
>        (slist (read-from-string s)))
>   (format t "~&slist: ~S" slist)
>   (format t "~&(equal x1 x2): ~S" (equal x1 x2))
>   (format t "~&(eval slist): ~S" (eval slist)))
>
> slist: (EQUAL X1 X2)
> (equal x1 x2): T
> EDITOR::EVALUATION-ERROR
> Error while evaluating: The variable X1 is unbound.
>
> Any help is appreciated.
>
> Thanks,
> Sheldon


Updated at: 2020-12-10 08:38 UTC