Function: with-slots

with-slots is a macro defined in eieio.el.gz.

Signature

(with-slots SPEC-LIST OBJECT &rest BODY)

Documentation

Bind SPEC-LIST lexically to slot values in OBJECT, and execute BODY.

This establishes a lexical environment for referring to the slots in the instance named by the given slot-names as though they were variables. Within such a context the value of the slot can be specified by using its slot name, as if it were a lexically bound variable. Both setf and setq can be used to set the value of the slot.

SPEC-LIST is of a form similar to let. For example:

  ((VAR1 SLOT1)
    SLOT2
    SLOTN
   (VARN+1 SLOTN+1))

Where each VAR is the local variable given to the associated SLOT. A slot specified without a variable name is given a variable name of the same name as the slot.

Probably introduced at or before Emacs version 28.1.

Source Code

;; Defined in /usr/src/emacs/lisp/emacs-lisp/eieio.el.gz
;;; Handy CLOS macros
;;
(defmacro with-slots (spec-list object &rest body)
  "Bind SPEC-LIST lexically to slot values in OBJECT, and execute BODY.
This establishes a lexical environment for referring to the slots in
the instance named by the given slot-names as though they were
variables.  Within such a context the value of the slot can be
specified by using its slot name, as if it were a lexically bound
variable.  Both setf and setq can be used to set the value of the
slot.

SPEC-LIST is of a form similar to `let'.  For example:

  ((VAR1 SLOT1)
    SLOT2
    SLOTN
   (VARN+1 SLOTN+1))

Where each VAR is the local variable given to the associated
SLOT.  A slot specified without a variable name is given a
variable name of the same name as the slot."
  (declare (indent 2) (debug (sexp sexp def-body)))
  (require 'cl-lib)
  ;; Transform the spec-list into a cl-symbol-macrolet spec-list.
  (macroexp-let2 nil object object
    `(cl-symbol-macrolet
         ,(mapcar (lambda (entry)
                    (let ((var  (if (listp entry) (car entry) entry))
                          (slot (if (listp entry) (cadr entry) entry)))
                      (list var `(slot-value ,object ',slot))))
                  spec-list)
       ,@body)))