[REBOL] problems with local vars??? Re:
From: bhandley:zip:au at: 16-Aug-2000 23:19
Hi Raimund,
The first thing is to understand that you can use my-local-string like a
variable, but it is not really a variable (in the sense of a pointer to
memory). It is a word that can refer to a value. The word my-local-string
exists in it's own right - so does the value of type string "that is local".
Doing an "assignment" associates the two.
With this in mind, Rebol does not "initialise" the variable - it actually
associates a word with a value. In C and other compiled languages when you
declare a variable you give the variable a datatype and when you assign
something to the variable your value is just a bunch of bits that conform to
the datatype. This is not the case with Rebol. In Rebol the value has the
type information. A word is a value too - a special type of value that can
be associated with another value. In Rebol everything is a value including
functions. So local-func is a word that refers to a value of type function.
Here's your function slightly edited
local-func: function [input][my-local-string][
my-local-string: ; This says make it so that my-local-string refers
to the next value. (1)
"that is local " ; This says create a string value. (2)
print append my-local-string input ; (3)
]
Both (1) and (2) are part of the function definition.
When (3) is actually executed, it in fact changes the value of (2). Why?
because when the line is evaluated, my-local-string is evaluted before the
append. My local string evaluates to the actual string stored in the
function definition.
You can see how the function definition has changed by calling your function
once and then using the command.
source local-func
Now, if you function read like this...
local-func2: function [input][my-local-string][
my-local-string: ; This says make it so that my-local-string refers
to the next value. (4)
copy "that is local " ; This says create a new string value that
is a copy of another. (5)
print append my-local-string input ; (6)
]
What would happen in (5) is a copy would be make of the string that is
stored inside the function definition and the copy would be "assigned" to
the word my-local-string. In this case when line (6) is executed the string
will change but the function will not because the function does not refer to
the copy.
Hope it helps.
Brett.