9

下面函数的目的是返回一个在两颗星之间插入参数值的字符串。

star-name: func [name /local stars] [
    stars: "**"
    insert next stars name
    stars
]
print star-name "test" ;*test*
print star-name "this" ;*thistest*, but what I really want is *this*  

我第二次调用该函数时,第一次调用的参数仍然插入。我知道答案是使用copy "**". 我的问题是,它不是在每次调用函数时都重新分配stars变量吗?"**"

4

2 回答 2

6

In the case of the function there is just one "**" string definition. That definition is used by Rebol load function just once, since load is run just once to translate the code to Rebol internal form - a block. It is true that the assignment occurs twice if you call the function twice, but the assignment does not create anything, it just makes the variable refer to the same string again.

In your comment you should notice that you actually have two "**" string definitions leading to two strings being created by load. If you use

code: [stars: "**" insert next stars something]
something: "this"
do code
something: "that"
do code

you will notice that there is just one string definition and while you do not have any function the behaviour is the same as it was when a function was used.

于 2013-08-09T09:19:06.053 回答
2

如果您在系列上使用 set-word,则默认行为是只为该系列分配一次内存。这使您可以将其用作在您发现的函数调用之间持续存在的静态变量。

如果您不想要这种行为,那么您需要每次显式复制该系列以创建一个新系列。

这是您可以执行此操作的另一种方式,因为不需要本地星星

star-name: func [ name ][
  rejoin [ "*" name "*" ]
]
于 2013-08-09T07:50:45.597 回答