Search code examples
common-lispclos

Common Lisp: How to check if a slot is bound? (CLOS)


Say we have a slot without :initform

(defclass foo ()
  ((x :reader x :initarg x)))

How can I check if slot x of an instance of foo is bound?

There is a way to do this with MOP, which I find very ugly. Is there an easier way?

I'd rather resort to:

(defclass foo ()
  ((x :reader x :initarg x :initform nil)))

and just check if it is nil or not -- in which case x may never be nil (ambiguous).


Solution

  • search for all symbols with SLOT in package CL:

    CL-USER 1 > (apropos "SLOT" "CL")
    
    SLOT-MISSING (defined)
    UNBOUND-SLOT-INSTANCE (defined)
    SLOT-VALUE (defined)
    SLOT-BOUNDP (defined)
    SLOT-EXISTS-P (defined)
    WITH-SLOTS (defined macro)
    SLOT-MAKUNBOUND (defined)
    UNBOUND-SLOT
    MAKE-LOAD-FORM-SAVING-SLOTS (defined)
    SLOT-UNBOUND (defined)
    

    I would guess that SLOT-BOUNDP does what you want. By looking at the Common Lisp HyperSpec we can verify this: