为什么变量不会从Red语言的循环中改变

时间:2017-09-23 03:43:23

标签: list variable-assignment rebol red

我想从循环中更改一系列变量,但以下代码无效:

a: 10
b: 20
c: 30
print reduce [a b c]              ; output is 10 20 30 as expected

varnames: [a b c]                 ; make a series of variables
foreach i varnames [              ; loop to convert each to 0
    i: 0
]

print "After conversion loop: "
print reduce [a b c]              ; values are still 10 20 30 (expected 0 0 0)

运行此代码后,我希望abc的值可以更改,但它们不会更改:

>> print reduce [a b c]   
10 20 30

问题出在哪里?

2 个答案:

答案 0 :(得分:3)

>> set varnames: [a b c] [10 20 30]
== [10 20 30]

>> foreach i varnames [set i 0]
== 0

>> reduce varnames
== [0 0 0]

你给了我一个来自循环的值,然后给它一个不同的值0,但实际上你没有改变我所指的那个词。 set允许您这样做。

答案 1 :(得分:2)

一个,但最短的解决方案

>> set [a b c] 0
== 0
>> reduce [a b c]
== [0 0 0]
再来一次

set set 'varnames [a b c] [0]
>> print probe varnames
[a b c]
0 0 0