[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: How to define a macro correctly?
From: |
Barry Margolin |
Subject: |
Re: How to define a macro correctly? |
Date: |
Wed, 08 Dec 2010 15:32:21 -0000 |
User-agent: |
MT-NewsWatcher/3.5.3b3 (Intel Mac OS X) |
In article <mailman.8.1287429628.15066.help-gnu-emacs@gnu.org>,
Johan Andersson <johan.rejeep@gmail.com> wrote:
> Hey,
>
> I want to create a macro that sets a variable value and then executes body.
> I know how to solve it, but I want to know which way is the best (more
> correct). I came up with these solutions:
>
> a)
> (defmacro mac (&rest body)
> `(progn
> (setq var t)
> ,@body))
>
> b)
> (defmacro mac (&rest body)
> (setq var t)
> `(progn ,@body))
>
> c)
> (defmacro mac (&rest body)
> (cons 'progn (cons (list 'setq 'var t) body)))
>
> I noticed that (using macroexpand) macro a and c expands to the same list. b
> however sets the variable in the macro and then only return the list body.
> What does that mean exactly, that I set the variable in the macro and do not
> return it as a list?
>
> What way is the best? Or is there some other way that is better?
>
> Thanks!
a and c are equivalent. The backquote expression in a is just shorthand
for the cons stuff you wrote in c (or something equivalent to it).
b is wrong. The setq happens once at compile time, not execution time.
You'll notice the difference when you byte-compile a file that uses the
macro.
--
Barry Margolin, barmar@alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***
*** PLEASE don't copy me on replies, I'll read them in the group ***
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- Re: How to define a macro correctly?,
Barry Margolin <=