Search code examples
common-lisp

Why did EVAL-WHEN with :LOAD-TOPLEVEL not run the body when I LOAD the file?


I have written this Lisp program:

(eval-when (:load-toplevel)
  (princ "Hello!"))

However, when I load the program, the body of the eval-when is not run.

$ sbcl
* (load "hello.lisp")
T
*

What is happening? In the eval-when, I used :load-toplevel to specify that its body should be run when I load the file. I am surprised that (princ "Hello!") did not run when I loaded the file.


Solution

  • From CLHS:

    The use of the situations :compile-toplevel (or compile) and :load-toplevel (or load) controls whether and when evaluation occurs when eval-when appears as a top level form in code processed by compile-file.

    Since you're not loading the compiled file, the :load-toplevel situation doesn't apply. Use :execute to execute code when the source is being loaded.