LispWorks User Guide and Reference Manual > 6 The Advice Facility

NextPrevUpTopContentsIndex

6.1 Defining advice

Each change that is required should be specified using the defadvice macro. This defines a new body of code to be used when the function is called; this piece of code is called a piece of advice. Consider the following example:

 CL-USER 71 > (defadvice
            (reverse print-advice :before)
            (the-list)
            (format t 
              "~%** Calling reverse on ~S **" 
              the-list))
NIL 
 
CL-USER 72 > (reverse '(l a m i n a))
 
** Calling reverse on (L A M I N A) ** 
(A N I M A L) 

In the above example you decided to print a message each time reverse is called. You called defadvice with a description of the function you wanted to alter, a name for the piece of advice, and the keyword :before to indicate that you want the code carried out before reverse is called. The rest of the call to defadvice specifies the additional behavior required, and consists of the lambda list for the new piece of advice and its body (the lambda list may specify keyword parameters and so forth). The advice facility arranges that print-advice is invoked whenever reverse is called, and that it receives the arguments to reverse , and that directly after this the original definition of reverse is called.

Pieces of advice may be given to be executed after the call by specifying :after instead of :before in the call to defadvice. So if you wished to add further code to be performed after reverse you could continue the session above as follows:

CL-USER 73 > (defadvice
              (reverse after-advice :after)
              (the-list)
              (format t
            "~%** After calling reverse on ~S **"
             the-list))
NIL 
 
CL-USER 74 > (reverse '("which" "way" "round"))
 
** Calling reverse on ("which" "way" "round") ** 
 
** After calling reverse on ("which" "way" "round") ** ("round" "way" "which") 
 
CL-USER 75 > 

Note that after-advice also receives the arguments to reverse when it is called.


LispWorks User Guide and Reference Manual - 22 Dec 2009

NextPrevUpTopContentsIndex