I am trying to learn Elisp, so I am reading the GNU Manual for Elisp. Everything so far is easy to understand, however when I read to the section of macro I encountered something I have a hard time understanding. I couldn't really find an adequate explanation neither:
For example, a simple macro program that increments the variable by 1:
(defmacro inc (var)
(list 'setq var (list '1+ var)))
I am not sure why there is '
symbol in front of setq
and 1+
? Won't this make them to a list of literal elements? (For example a list containing three elements (setq var (1+ var))
Why can't I write:
; this seems more reasonable to me
(defmacro inc (var)
(setq var (1+ var))
I am not really sure how list
works here and it seems strange to me using list
here. Can someone explain to me?
Won't this make them to a list of literal elements? (For example a list containing three elements
(setq var (1+ var))
Precisely so (if we substitute the actual argument for var
).
A macro generates/returns code.
This is the "expansion" phase of the macro, which typically takes place during byte-compilation of the elisp file.
So as far as the contents of that byte-compiled .elc file are concerned, there's no difference between you having used either of these things in your .el source file:
(inc foo)
(setq foo (1+ foo))
I.e. In both cases the code which gets byte-compiled is (setq foo (1+ foo))
Outside of byte-compilation, a macro might be expanded when the .el file is load
ed or, failing that, on-demand right before the expanded code needs to be evaluated (but you should always assume the expansion happens completely independently of the subsequent evaluation).