评估"变量变量"

Dar*_*don 5 rebol

我用以下方法创建一个动态变量(PHP用语中的"变量变量"):

foo: "test1"
set to-word (rejoin [foo "_result_data"]) array 5
Run Code Online (Sandbox Code Playgroud)

但是,如何动态获取名为"test1_result_data"的结果变量的值?我尝试了以下方法:

probe to-word (rejoin [foo "_result_data"])
Run Code Online (Sandbox Code Playgroud)

但它只返回"test1_result_data".

小智 8

由于您的示例代码是REBOL 2,您可以使用GET来获取单词的值:

>> get to-word (rejoin [foo "_result_data"])
== [none none none none none]
Run Code Online (Sandbox Code Playgroud)

REBOL 3处理上下文的方式与REBOL 2不同.因此,在创建新单词时,您需要明确处理它的上下文,否则它将没有上下文,当您尝试设置它时会出现错误.这与REBOL 2形成对比,REBOL 2默认设置单词的上下文.

因此,您可以考虑使用REBOL 3代码,如下所示来设置/获取动态变量:

; An object, providing the context for the new variables.
obj: object []

; Name the new variable.
foo: "test1"
var: to-word (rejoin [foo "_result_data"])

; Add a new word to the object, with the same name as the variable.
append obj :var

; Get the word from the object (it is bound to it's context)
bound-var: in obj :var

; You can now set it
set :bound-var now

; And get it.
print ["Value of " :var " is " mold get :bound-var]

; And get a list of your dynamic variables.
print ["My variables:" mold words-of obj]

; Show the object.
?? obj
Run Code Online (Sandbox Code Playgroud)

将此作为脚本运行会产生:

Value of  test1_result_data  is  23-Aug-2013/16:34:43+10:00
My variables: [test1_result_data]
obj: make object! [
    test1_result_data: 23-Aug-2013/16:34:43+10:00
]
Run Code Online (Sandbox Code Playgroud)

上面使用IN的替代方法可能是使用BIND:

bound-var: bind :var obj
Run Code Online (Sandbox Code Playgroud)


kea*_*ist 5

在Rebol 3中,绑定与Rebol 2不同,并且有一些不同的选项:

最笨拙的选择是使用load:

foo: "test1"
set load (rejoin [foo "_result_data"]) array 5
do (rejoin [foo "_result_data"])
Run Code Online (Sandbox Code Playgroud)

有一个加载intern使用的函数 - 可以用来绑定和检索来自一致上下文的单词:

foo: "test1"
set intern to word! (rejoin [foo "_result_data"]) array 5
get intern to word! (rejoin [foo "_result_data"])
Run Code Online (Sandbox Code Playgroud)

否则to word!会创建一个不易使用的未绑定字.

第三种选择是用于bind/new将单词绑定到上下文

foo: "test1"
m: bind/new to word! (rejoin [foo "_result_data"]) system/contexts/user
set m array 5
get m
Run Code Online (Sandbox Code Playgroud)