Question

So If I have a defclass object and I make an instance of it and place it inside an array. How do I get the value of its slots inside the array?

I've tried:

(slot-value (aref *array* 0) :name)

I guess I am just not understanding how to access an object that is inside an array.

I can print the object in an unreadable form using (format t) but is there a way to print an object and all the slots in a form I can actually understand?

(defun generate-object (name)
  (let ((a (make-instance 'person
                          :name name)))
    (setf (aref *array* 0) a)))

it places the object inside the array but it seems that the slot is not being created?

This causes the problem:

(defclass person ()
  ((name :accessor name
         :reader read-name
         :initarg :name)))

(defvar *array* 0)
(setf *array* (make-array 20))

(defun generate-object (name)
  (let ((a (make-instance 'person
                          :name name)))
    (setf (aref *array* 0) a)))
Was it helpful?

Solution

The slot name needs to be a symbol that is syntactically valid as a variable name. Try 'name instead of :name .

(slot-value (aref *array* 0) 'name)

Look at the examples here.

OTHER TIPS

While possible, it is not recommended to use slot-value outside of the low-level class-specific code (like initialize-instance methods etc.).

You should instead add accessors to your slots and use those. For example:

(defclass foo ()
  ((bar :reader foo-bar
        :initarg :bar)))

This defines a class foo with a slot bar. You can initialize the slot upon object instantiation with the :initarg name:

(let ((my-foo (make-instance 'foo :bar "baz")))
  #| whatever |#)

You can read the slot value with the defined :reader:

(let ((my-foo (make-instance 'foo :bar "baz")))
  (foo-bar my-foo))

It doesn't matter where you get your foo from, of course. Imagine you have an array foo-array which is filled with foos. To get the bar slot value of the fourth foo in that array:

(foo-bar (aref foo-array 3))

If you also want to set the value, use an :accessor instead of the :reader slot option.
Then you can use it as a place:

(let ((my-foo (make-instance 'foo)))
  (setf (foo-bar my-foo) "quux"))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top