[REBOL] Re: How do I dynamically modify an object?
From: joel:neely:fedex at: 14-Jan-2003 17:35
Hi, Ed,
At the risk of offending some Perlophobes among us... ;-)
Ed Dana wrote:
> How do I (Can I?) add Address to an _existing_ object *after* that
> object has been created.
>
One way of managing an object's namespace in Perl is to store the
attributes explicitly within a key/value structure (hash, in Perl).
We can pull the same trick here, at the cost of a little explicit
machinery to manage that structure, as follows:
example: make object! [
name: "Fred"
age: 5000000
dynamic: []
dynamic-get: func ['key [word!]] [select dynamic key]
dynamic-set: func ['key [word!] val [any-type!] /local where] [
either found? where: find dynamic key [
change next where val
][
append/only append dynamic key val
]
val
]
]
So that EXAMPLE now has "static" attributes, such as NAME or AGE,
and a collection of "dynamic" attributes. First the static ones:
>> example/name
== "Fred"
>> example/age
== 5000000
Then let's add a dynamic one (after checking to make sure that it
is not already there).
>> example/dynamic-get address
== none
>> example/dynamic-set address "123 Bedrock Way"
== "123 Bedrock Way"
>> example/dynamic-get address
== "123 Bedrock Way"
Once a dynamic attribute has been added via DYNAMIC-SET we can use
the standard path notation to retrieve...
>> example/dynamic/address
== "123 Bedrock Way"
... or even to redefine it!
>> example/dynamic/address: "456 Slag Street"
== [address "456 Slag Street"]
>> example/dynamic-get address
== "456 Slag Street"
>> source example
example:
make object! [
name: "Fred"
age: 5000000
dynamic: [address "456 Slag Street"]
dynamic-get: func ['key [word!]][select dynamic key]
dynamic-set: func ['key [word!] val [any-type!] /local where][
either found? where: find dynamic key [
change next where val
] [
append/only append dynamic key val
]
val
]
]
>> example/dynamic/address
== "456 Slag Street"
That's not exactly what you asked for, but it's at least a distant
cousin.
> And why would I want to do this? Why not? =)
>
Just because!
After all, one would expect a dynamic "object language" to be very
flexible in what one can do with objects, right! ;-)
-jn-