REBOL 3 Docs | Guide | Concepts | Functions | Datatypes | Errors |
TOC < Back Next > | Updated: 6-Feb-2009 Edit History |
An object can contain variables that refer to functions that are defined within the context of the object. This is useful because the functions are encapsulated within the context of the object, and can access the other variables of the object directly, without a need for a path.
As a simple example, the example object can include functions for computing new values within the object:
example: make object! [ var1: 10 var2: var1 + 10 var3: now/time set-time: does [var3: now/time] calculate: func [value] [ var1: value var2: value + 10 ] ]
Notice in the example that the functions are able to refer to the variables of the object directly, rather than as paths. That is possible because the functions are defined within the same context as the variables they access.
To set a new time, use:
example/set-time
This example evaluates the function that sets var3 to the current time.
To calculate new values for var1 and var2 , use:
example/calculate 100
print example/var2
110
In the case of the bank-account object, the functions for deposit and withdraw can be added to the current definition:
bank-account: make bank-account [ deposit: func [amount [money!]] [ balance: balance + amount ] withdraw: func [amount [money!]] [ either negative? balance [ print ["Denied. Account overdrawn by" absolute balance] ][balance: balance - amount] ] ]
In the example, notice that the functions are able to refer to the balance directly within the object. That's because the functions are part of the object's context.
Now if a new account is made, it will contain functions for depositing and withdrawing money. For example:
lily: make-account "Lily" "Lakeswimmer" $1000
print lily/balance
$1010.00
lily/deposit $100
print lily/balance
$1110.00
lily/withdraw $2000
print lily/balance
-$890.00
lily/withdraw $2.10
Denied. Account overdrawn by $890.00
TOC < Back Next > | REBOL.com - WIP Wiki | Feedback Admin |