emacs-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Using the content of a dynamic variable in a macro


From: tomas
Subject: Re: Using the content of a dynamic variable in a macro
Date: Sat, 25 Feb 2023 10:40:18 +0100

On Sat, Feb 25, 2023 at 09:34:07AM +0100, Damien Cassou wrote:
> I tried to send the mail below to help-gnu-emacs@gnu.org (without being
> subscribed) but it never reached the archive:
> https://lists.gnu.org/archive/html/help-gnu-emacs/2023-02/threads.html.
> 
> Hi,
> 
> I'm wondering why the code below works but won't compile.
> 
> foo.el:
>   (defvar foo-var '((message "hello world")))
>   
>   (defmacro foo-macro ()
>     `(progn
>        ,@foo-var))
>   
>   (defun foo-fun ()
>     (foo-macro))
> 
> 
> $ emacs --batch -l foo.el --eval '(foo-fun)'
> hello world
> 
> $ emacs --batch --eval '(find-file "foo.el")' --eval 
> '(emacs-lisp-byte-compile)'
> In toplevel form:
> foo.el:32:1: Error: Symbol’s value as variable is void: foo-var
> 
> Why isn't the compiler aware of the foo-var variable?

Because the (dynamic) variable comes into existence later,
at run time (at compile time the (defvar ...) hasn't yet
been executed).

You might try to wrap your defvar in an (eval-when-compile ...)
form. Other more knowledgeable folks around here might chime
in whether (or when) this may be a good idea or not.

But the main takeaway is that compile time (and thus macro
expansion time) and run time are kind of different "worlds".

(See also eval-and-compile, but in this case you'll be fine
with eval-when-compile, I think)

Cheers
-- 
t

Attachment: signature.asc
Description: PGP signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]