How to write a (simple) macro?

I need to write a macro (with-hooks (monster method who what) &body body)for the game I am writing. A monster is a CLOS object, a method, and who is a string, and what is a function (notation #). Macroextraction will be something like

(add-hook monster method who what)
,@body
(remove-hook monster method who)

I have absolutely no idea how to write such a macro, and I would appreciate some help. I have a terrible feeling that it is easy, and I am a little ignorant.

+5
source share
1 answer

I would write it like this:

(defmacro with-hooks ((monster method who what) &body body)
  (let ((monster-var (gensym))
        (method-var (gensym))
        (who-var (gensym))
        (what-var (gensym)))
    `(let ((,monster-var ,monster) ; dummy comment
           (,method-var ,method)
           (,who-var ,who)
           (,what-var ,what))
        (add-hook ,monster-var ,method-var ,who-var ,what-var)
        (unwind-protect
           (progn ,@body)
          (remove-hook ,monster-var ,method-var ,who-var)))))

Some notes:

  • something-var , monster, method, who, what ( ) .
  • gensym , ,
  • unind-protect , remove-hook (, - - ).
+10

All Articles