是否可以在 rebol/red 中动态创建 LOCAL 变量?

Is it possible to create LOCAL variable dynamically in rebol / red?

在 rebol/red 中使用 set like

可以很容易地动态创建 GLOBAL 变量
i: 1
myvarname: rejoin ["var" i]
set to-word myvarname 10
var1

但是 var1 是全局的。如果我想在函数内动态创建 var1 并将其设置为 LOCAL 以避免与一些同名的全局变量发生冲突怎么办?

在javascript中可以: How to declare a dynamic local variable in Javascript

不确定在 rebol/red 中是否可行?

在 Rebol 中,有 USE:

x: 10
word: use [x] [
   x: 20
   print ["Inside the use, x is" x]
   'x ;-- leak the word with binding to the USE as evaluative result
]
print ["Outside the use, plain x is" x]
print ["The leaked x from the use is" get word]

那会给你:

Inside the use, x is 20
Outside the use, x is 10
The leaked x from the use is 20

应该预先警告,它的工作方式是有效地创建 make object! [x: none]。然后它深入 USE 的主体,寻找 ANY-WORD!名为 x(或 X,大小写无关紧要)...并将它们绑定到该对象!

这有几个烦人的特性:

  • 绑定的枚举和更新需要时间。如果你在一个循环中,每次访问都需要这个时间。

  • 创建对象!创建两个系列节点,一个用于跟踪键 (x),一个用于跟踪变量 (20)。同样,如果您处于循环中,则每次通过该循环都会创建两个系列节点。正如循环外的 GET 所示,这些节点将一直存在,直到垃圾收集器决定不再需要它们。

  • 您可能想说 使用 [x] 代码 并且不破坏代码中的绑定,因此在更改之前需要对主体进行深度复制.

深度绑定的不良特性导致 Red change the language semantics 像 FOR-EACH 这样的结构。它目前也没有 USE 构造,出于某些相同的推理,可能被认为最好避免使用。

(注意:Rebol 方面正在研究新的方法来使性能达到 "acceptable cost",这可能足以在将来使用。这将是用于 specific binding).

的技术

在 Red 中你有 function,在 Rebol2 中你有 funct。两者都自动创建局部变量词。这里有一个 Rebol2

的例子
>> for num 1 100 1 [ 
[      set to-word rejoin ["f" num] funct [] compose/deep [
[            print [ "n =" n:  (num) ]
[          ]
[    ]
>> f1
n = 1
>> f2
n = 2
>> n
** Script Error: n has no value
** Near: n

是怎么做到的,用source funct

看看