12

I have a class like this one

(defclass shape ()
 ((color :initform :black)
 (thickness :initform 1)
 (filledp :initform nil)
 (window :initform nil)))

Is there a function in common-lisp how to get a list of those slots if i only know instance of this class?

4
  • 1
    Closely related: stackoverflow.com/q/38452350/124319
    – coredump
    Commented Nov 22, 2016 at 13:58
  • Alright, thank you for answers. But i have another problem. I need to know every method from class. Even methods from inherited class. (defclass point (shape) ((x :initform 0) (y :initform 0))) Is there a way, how to get it ?
    – Micky
    Commented Dec 4, 2016 at 12:02
  • See the linked question.
    – coredump
    Commented Dec 4, 2016 at 12:16
  • But I can not use any external libraries.
    – Micky
    Commented Dec 4, 2016 at 12:49

1 Answer 1

21

Many Common Lisp implementations support the CLOS Meta-object Protocol. This provides introspective operations for classes, slots and other meta objects.

In LispWorks the corresponding functions are directly accessible in the package CL-USER.

CL-USER 139 > (defclass shape ()
                ((color :initform :black)
                 (thickness :initform 1)
                 (filledp :initform nil)
                 (window :initform nil)))
#<STANDARD-CLASS SHAPE 40202910E3>

CL-USER 140 > (mapcar #'slot-definition-name
                      (class-direct-slots (class-of (make-instance 'shape))))
(COLOR THICKNESS FILLEDP WINDOW)

The functions slot-definition-name and class-direct-slots are defined by the Meta Object Protocol for CLOS and are supported in many Common Lisp implementations - just the package they are in may differ. In SBCL for example one might find them in the package SB-MOP.

From a class we can get the list of direct slots. Direct slots are the slots which are directly defined for that class and which are not inherited. If you want to get a list of all slots, then use the function class-slots.

Slot here means that we get a slot definition object, which describes the slot. To get the name of the slot, you have to retrieve the name from the slot definition object using the function slot-definition-name.

3
  • 1
    @Micky See also github.com/pcostanza/closer-mop. You can also use (apropos 'slot-definition-name) to find out in which packages those functions are defined in your implementation.
    – coredump
    Commented Nov 30, 2016 at 10:15
  • 1
    @coredump thanks, that helped me figure out how to run this on sbcl:
    – Pascal
    Commented Nov 30, 2016 at 10:36
  • 2
    (mapcar #'sb-mop:slot-definition-name (sb-mop:class-direct-slots (class-of (make-instance 'shape))))
    – Pascal
    Commented Nov 30, 2016 at 10:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.