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

Content deleted Content added
Added BBC BASIC
added a correct (instance-specific slot) example; should I remove the old one? (it is instructive as well, adding a slot to all instances...)
Line 1,064:
 
=={{header|Smalltalk}}==
the following addSlot function creates an anonymus class with the additional slot, defines accessor methods and clones a new instance from the given object which becomes the old one.
This preserves object identity. This uses a block for compactness; in a real world application, the addSlot code would be added as an extension to the Object class, though.
{{works with|Smalltalk/X}}
<lang smalltalk>|addSlot p|
 
addSlot :=
[:obj :slotName |
|c nObj|
c := obj class
subclass:(obj class name,'+') asSymbol
instanceVariableNames:slotName
classVariableNames:''
poolDictionaries:'' category:nil
inEnvironment:nil.
c compile:('%1 ^ %1' bindWith:slotName).
c compile:('%1:v %1 := v' bindWith:slotName).
nObj := c cloneFrom:obj.
obj become:nObj.
].</lang>
create a 2D Point object, add a z slot, change and retrieve the z-value, finally inspect it (and see the slots).
<lang smalltalk>p := Point x:10 y:20.
addSlot value:p value:'z'.
p z:30.
p z.
p z:40.
p inspect
</lang>
 
{{incorrect|Smalltalk|It extends the class (adds a new instance var and new method that will exists even in brand new future instances of that class), not only the particular instance. -- The description of the problem must be reworded then, as it
asks for adding variables to the class, not the instance.}}