Let's assume:
(defmacro testing (&optional var)
`(list 'this 'is
,@(when (consp var) `('a 'list))))
when called:
>(testing 2)
(THIS IS)
>(testing (list 1 2))
(THIS IS A LIST)
which is what I wanted. But now, when I pass a parameter that is a list:
>(defparameter bla (list 1 2 3))
BLA
>(testing bla)
(THIS IS)
which I suppose is because the macro would check (consp bla)
where bla is a symbol, instead of the list? How do I prevent this?
Thanks
The problem here is that the expression
is evaluated at compile time, when you only have literal (unevaluated) values of arguments. In your case:
2
,(list 1 2)
, andbla
.The only solution to this, that I'm aware of, is to use
eval
. This particular example can be changed as follows:But, I think, you'll agree, that its really ugly. And it won't work if you want to use lexical variables. Usually, there are ways to reformulate the problem, so that such perversions aren't needed.
You could do something like:
So
var
will be evaluated at run time (not compile time).var
only appears one time in the expansion of the macro, but if it appeared more than once, you would have to use a gensym.EDIT: If you don't want to type
'(this is)
twice, do this:Don't use
eval
, it's slow, and completely unnecessary. By substitutingvar
into the macro expansion, it will naturally be evaluated at run-time. If you use eval, you will be doing something like this:Every time that executes, it will build up a list representing the code and compile it before running it. (Hopefully this isn't in a loop!) If you just use a macro which generates straightforward code (without
eval
), it will compile only once.