I'm having a hard time understanding exactly how macro expansion works. What is the difference in how the elisp interpreter handles these two snippets of code?
(defmacro foo (arg)
(message "arg is: %s" arg))
(foo "bar")
and:
(defmacro foo (arg)
`(message "arg is: %s" ,arg))
(foo "bar")
message
both displays a message and returns it.(defconst zzz 123)
(defmacro zzz1 (arg)
`(insert (format "arg is: %s" ,arg)))
(defmacro zzz2 (arg)
(insert (format "arg is: %s" arg)))
Evaluate the code above using C-x C-e after each of the 3 forms.
Now evaluate these:
(zzz1 zzz)
The interpreter...
zzz1
(insert (format "arg is: %s" zzz))
"arg is: 123"
into the current buffer, and returns nil
(seen in the echo area at the bottom)(zzz2 zzz)
The interpreter...
zzz2
"arg is: zzz"
in the current buffer and returns nil
nil
to nil
(seen in the echo are at the bottom)The most important "take-away" here is that macros are just functions which operate on code before the interpreter (of compiler) kicks in.
These functions take their arguments unevaluated (i.e., in both zzz1
and zzz2
, arg
is zzz
, not 123
).
They are evaluated like any other lisp function (e.g., they can have macro forms in their bodies; the body is wrapped in an implicit progn
; &c).
Their return value is evaluated by the interpreter instead of the original form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With