Next: , Previous: , Up: Problems with Macros   [Contents][Index]


18.6.3 Evaluating Macro Arguments in Expansion

Another problem can happen if you evaluate any of the macro argument expressions during the computation of the expansion, such as by calling eval (see Eval). If the argument is supposed to refer to the user’s variables, you may have trouble if the user happens to use a variable with the same name as one of the macro arguments. Inside the macro body, the macro argument binding is the most local binding of this variable, so any references inside the form being evaluated do refer to it. Here is an example:

(defmacro foo (a)
  (list 'setq (eval a) t))
     ⇒ foo
(setq x 'b)
(foo x) → (setq b t)
     ⇒ t                  ; and b has been set.
;; but
(setq a 'c)
(foo a) → (setq a t)
     ⇒ t                  ; but this set a, not c.

It makes a difference whether the user’s variable is named a or x, because a conflicts with the macro argument variable a.

Another reason not to call eval in a macro definition is that it probably won’t do what you intend in a compiled program. The byte-compiler runs macro definitions while compiling the program, when the program’s own computations (which you might have wished to access with eval) don’t occur and its local variable bindings don’t exist.

The safe way to work with the run-time value of an expression is to put the expression into the macro expansion, so that its value is computed as part of executing the expansion.


Next: , Previous: , Up: Problems with Macros   [Contents][Index]