[REBOL] Re: How do I dynamically modify an object?
From: joel:neely:fedex at: 14-Jan-2003 15:09
Hi, Ed,
The short answer is, "You can't!"
Ed Dana wrote:
> Using the examples from the REBOL On-line dictionary:
> >> Example: Make Object! [ Name: "Fred" Age: 5000000 ]
> >> Get in Example 'Name
> == "Fred"
> >> Set in Example 'Name "Fred Flintstone"
> == "Fred Flintstone"
>
> How do I dynamically add to example, after it has been created,
> Address: "123 Bedrock Path".
>
> I tried using 'Set, 'Make and a couple other functions, but they
> didn't work. I was probably using them wrong. :)
>
In previous discussions, the following approach has been taken:
>> example: make object! [name: "Fred" age: 5000000]
>> example/name
== "Fred"
>> example/name: "Barney"
== "Barney"
>> source example
example:
make object! [
name: "Barney"
age: 5000000
]
>> example: make example [address: "123 Bedrock Path"]
>> source example
example:
make object! [
name: "Barney"
age: 5000000
address: "123 Bedrock Path"
]
But the obvious flaw is that EXAMPLE has now been set to a *new*
object constructed from the original and the expanded spec block.
That didn't change the original object at all. REBOL doesn't have
AFAICT any way to expand the context of an object (or function) after
the original definition. To show that the original did not change,
just capture a spare reference to it, as below:
>> otherref: example: make object! [name: "Fred" age: 5000000]
and then evaluate the same expressions as above:
>> example/name
== "Fred"
>> example/name: "Barney"
== "Barney"
>> example: make example [address: "123 Bedrock Path"]
>> source example
example:
make object! [
name: "Barney"
age: 5000000
address: "123 Bedrock Path"
]
then look at the spare reference:
>> source otherref
otherref:
make object! [
name: "Barney"
age: 5000000
]
Just to prove that ADDRESS is only valid for the *new* object...
>> otherref/address
** Script Error: Invalid path value: address
** Where: halt-view
** Near: otherref/address
>> example/address
== "123 Bedrock Path"
Some other languages (including Perl and Python) allow new attributes
to be added to an existing object after initial creation is long past.
While this does open the (another ;-) door to mis-use via the creation
of values that no longer resemble their original source code, it is
certainly an interesting concept for a dynamic language (and one can
use reflection/introspection to manage/follow such changes).
-jn-
--
----------------------------------------------------------------------
Joel Neely joelDOTneelyATfedexDOTcom 901-263-4446