[REBOL] problems with local vars??? Re:
From: joel:neely:fedex at: 16-Aug-2000 4:39
Hi, Raimund,
You've encountered the First Koan of REBOL. Use of literal strings
gives you the actual string, not a copy.
The first phrase in your function
my-local-string: "that is local "
makes the local word my-local-string refer to the second element of
the function's body. When you subsequently say
print append my-local-string input
the append is operating on the string that is the second element of
the function's body. Therefore the changes persist between invocations
of the function.
The gotcha is that in some other languages, assigning a string to a
variable does an implicit copy, whereas in REBOL, you must ask for the
copy operation if you want it. Therefore, the following version of your
function probably does what you expected:
--------------------------------------
REBOL []
local-func: function [input][my-local-string][
my-local-string: copy "that is local "
print append my-local-string input
]
local-func "Call 1"
local-func "Call 2"
print my-local-string
-------------------------------------
This is also true of blocks; if you want to construct a block within
a function (with no persistence of content), you likely will want to
initialize it with
my-local-block: copy []
before putting stuff into it.
The issue here is one of the meaning of literal values (strings, blocks,
etc.) in REBOL, and is not specific to functions.
>> stuff: [blk: [] append blk more-stuff print mold stuff]
== [blk: [] append blk more-stuff print mold stuff]
>> more-stuff: "Hello, world!"
== "Hello, world!"
>> do stuff
[blk: ["Hello, world!"] append blk more-stuff print mold stuff]
>>
Here we see that, without reference to function or context issues, the
literal block in the second position of stuff is modified.
-jn-
[raimund--swol--de] wrote: