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-

[EMAIL PROTECTED] wrote:
> 
> Hi,
> 
> I have quite some problems with the scope of local variables. The following
> script does point it out:
> 
> --------------------------------------
> REBOL []
> 
> local-func: function [input][my-local-string][
>   my-local-string: "that is local "
>   print append my-local-string input
> ]
> 
> local-func "Call 1"
> local-func "Call 2"
> 
> print my-local-string
> 
> -------------------------------------
> 
> raimund@linux:~/Development/rebol/Tests > rebol test_locals.r
> that is local Call 1
> that is local Call 1Call 2
> ** Script Error: my-local-string has no value.
> ** Where: print my-local-string
> >>
> 
> The results suggest that locals are handled like static vars in C is that
> correct? Why does the assignemnt to my-local-string at the start of the
> local-func not inititalize the local?
> 
> Can anyone point me to some more info about this issue?
> 
> Thanx
> 
> Raimund
> 
> <--------------------------------------------->
> 42 war schon immer einge gute Antwort;-))

Reply via email to