Reputation: 315
So I wanted to remake a program that uses lists for containing objects and replace the lists with arrays.
And I ran into a problem in which my object is of the same instance
(setq arr (make-array 3 :initial-element (make-instance 'object) :adjustable t :fill-pointer 3))
after this code's execution
all of the objects in the array are the same and the interpreter gives me this
#(#<OBJECT {1002DFDD23}> #<OBJECT {1002DFDD23}> #<OBJECT {1002DFDD23}>)
I know other ways to do this but still I want to know why does this happen?
and if it's no trouble what does #<OBJECT {1002DFDD23}
mean as a whole and is this some sort memory address?
Upvotes: 0
Views: 175
Reputation: 139241
Common Lisp HyperSpec: Function MAKE-ARRAY:
If initial-element is supplied, it is used to initialize each element of new-array
Upvotes: 2
Reputation: 4360
make-array
is a function. It’s arguments are evaluated before calling.
The following are equivalent:
(make-array 3
:initial-element (make-instance 'object)
:adjustable t
:fill-pointer 3))
And
(let ((a 3)
(b :initial-element)
(c (make-instance 'object))
(d :adjustable)
(e t)
(f :fill-pointer)
(g 3))
(make-array a b c d e f g))
Upvotes: 4
Reputation: 51501
The form (make-instance 'object)
is evaluated exactly once on invocation of your code. The result is used as initial value for each element of the array. It may help to see the singular word initial-element
(not -elements
), and that operators starting with make-
are usually functions and thus all arguments are evaluated before invocation.
The output #<OBJECT {1002DFDD23}>
is for an unreadable object. This is indicated by the #<
syntax, which is defined to signal an error when trying to read
it (http://clhs.lisp.se/Body/02_dht.htm). It is usually produced by print-unreadable-object
, which is usually used when defining methods for print-object
. The exact output is thus implementation or user defined (whoever wrote a print-object
method for that particular class). It will by default most likely contain the class name and something like a memory reference or address.
For completeness, I like to use map-into
:
(map-into (make-array 3 :adjustable t :fill-pointer 3)
(lambda () (make-instance 'object)))
to get an array initialized with distinct objects.
Upvotes: 6