Objects


An object is a container that groups data and/or functions within one variable. To access an object's attribute in Red, we use a slash (/) as a separator. This is unusual as most languages use a dot, but once you get used to it, it seems more intuitive as it is similar to a path.

Creating an object:

make object! , context & object

You may use make object! object or context to create an object. They are the same command. object and context are just shortcuts to make object!.

10
20
8
John
3333-3333
>>

Evaluation is done only when creating an object! Notice that the print command in the code below is not executed when the object is accessed:

>> myobject: object [print "hello" a: 1 b: 2]
hello
== make object! [
    a: 1
    b: 2
]
>> myobject/a
== 1
>>

Self reference:

When an object must do a reference to itself, we use a special keyword named self :

x: 10
y: 20
f: func [a b][a + b]
autoanalisys: func [][print self]
>>

Cloning an object and inheritance:

Simply assigning an object to another only creates a copy of the pointer to that object. If the original changes, the second also changes:

>> a: object [x: 10]
                                          ;lines of the console deleted for the sake of clarity.
>> b: a
                                          ;lines of the console deleted for the sake of clarity.
>> a/x: 20
== 20
>> b/x
== 20              ;changed too!
>>

To make a true copy of an object, we use the word copy:

>> a: object [x: 10]
                                           ;lines of the console deleted for the sake of clarity.
>> b: copy a
                                           ;lines of the console deleted for the sake of clarity.
>> a/x: 20
== 20
>> b/x
== 10             ;NO change! b is a true copy.
>>

If we want to create a new object that inherits the first object , we use: make <original object> <new specifications>:

x: 3
y: 12
>>

find & select - for objects

find simply checks if the field exists, returning true or none .

select does the same checking, but if the field exists, returns its value.

true
44
none
none
>>

Notice that both look for the word (indicated by the ' symbol preceding it), not the variable itself. The variable would be accessed by a simple path like obj/a.

results matching ""

    No results matching ""