zinkpro45
zinkpro45

Reputation: 37

How to return the value and name of a variable in Common Lisp

I'm trying to write a macro to return a variable's name and value in common lisp. How do I return the name and value of a variable in a LISP macro?

So something like

(RETURNVAL (x))

would return

x has value 5

Upvotes: 3

Views: 645

Answers (1)

Joshua Taylor
Joshua Taylor

Reputation: 85833

(defmacro returnval (x)
  `(format t "~a has value ~a." ',x ,x))

CL-USER> (defparameter *forty-two* 42)
*FORTY-TWO*
CL-USER> (returnval *forty-two*)
*FORTY-TWO* has value 42.
NIL
CL-USER> (let ((x 5))
           (returnval x))
X has value 5.
NIL

If you really want that extra set of parens around the form, you can do that, too:

(defmacro returnval ((x))
  `(format t "~a has value ~a." ',x ,x))

CL-USER> (returnval (*forty-two*))
*FORTY-TWO* has value 42.
NIL
CL-USER> (let ((x 5))
           (returnval (x)))
X has value 5.
NIL

Upvotes: 3

Related Questions