Re: modifying the behavior of slot accessors

From: Erick Gallesio <>
Date: Fri, 26 Feb 1999 15:46:09 +0100 (CET)

Brian Denheyer writes:
> Here is a class :
> (define-class <foo> ()
> ((read-only :accessor read-only)
> (value :accessor value)))
> Let's say that I want to control the way value is accessed based on
> the value of read-only, so that if it is true and the program tries to
> set a slot it won't work. It seems to me the proper way to do this is
> to make value a virtual slot and modify the accessors :
> (value :accessor value
> :allocation :virtual
> :slot-ref
> (lambda (self) (slot-ref self 'value)))
> whoops ! the accessor is now infinitely recursive.
> Obviously I can get around this by using define-method to create
> read/writer methods, but it seems more elegant to do it the way I want
> to. Is it possible ?


In fact STklos define a particular kind of slots called active
slots. An active slot is a slot whose access can be controlled before
or after reading (as well as before/after writing).
For that,you give a function for each of the 4 hook that you want to
set. In the case of the "before-slot-set!" function, the value that it
returns is used to know if the slot must be set (the slot is not set
if it returns #f).
So your class can be written as

    (define-class <foo> ()
     ((read-only :accessor read-only :init-form #t)
      (value :accessor value
             :allocation :active
             :before-slot-set! (lambda(o v)
                                 (not (slot-ref o 'read-only))))
     :metaclass <active-metaclass>)

The slot is active because of its allocation scheme (:active here) and
only the before-slot-set! function is given. Here the function just
forbid to set the value slot if read-only slot is not false. Of course
you can add error message or other processing if needed.

Hope it helps.

                -- Erick
Received on Fri Feb 26 1999 - 15:42:58 CET

This archive was generated by hypermail 2.3.0 : Mon Jul 21 2014 - 19:38:59 CEST