Jump to content

Add a variable to a class instance at runtime: Difference between revisions

added better CL code
(added better CL code)
Line 73:
 
=={{header|Common Lisp}}==
 
This version adds a new slot only to one instance, not to the whole class.
 
{{libheader|Closer to MOP}}
 
<lang lisp>(defun augment-instance-with-slots (instance slots)
(change-class instance
(make-instance 'standard-class
:direct-superclasses (list (class-of instance))
:direct-slots slots)))</lang>
 
Example:
 
<lang lisp>CL-USER> (let* ((instance (make-instance 'foo :bar 42 :baz 69))
(new-slots '((:name xenu :initargs (:xenu)))))
(augment-instance-with-slots instance new-slots)
(reinitialize-instance instance :xenu 666)
(describe instance))
#<#<STANDARD-CLASS NIL {1003AEE2C1}> {1003AEE271}>
[standard-object]
 
Slots with :INSTANCE allocation:
BAR = 42
BAZ = 69
XENU = 666</lang>
 
The following REPL transcript (from [[LispWorks]]) shows the definition of a class <code>some-class</code> with no slots, and the creation of an instance of the class. The first attempt to access the slot named <code>slot1</code> signals an error as there is no such slot. Then the class is redefined to have such a slot, and with a default value of 23. Attempting to access the slot in the preëxisting instance now gives the default value, since the slot has been added to the instance. This behavior is specified in [http://www.lispworks.com/documentation/HyperSpec/Body/04_cf.htm §4.3.6 Redefining Classes] of the [http://www.lispworks.com/documentation/HyperSpec/Front/index.htm HyperSpec].
Cookies help us deliver our services. By using our services, you agree to our use of cookies.