在Rebol中以编程方式检索函数参数

时间:2014-07-25 00:28:20

标签: rebol rebol2

这适用于shell级别:

>> a: "hello" 
== "hello"
>> get to-lit-word "a"
== "hello"

但在这样的函数中:

f: func [ arg1 ] [
    v1: get 'arg1
    ? v1
    v2: get to-lit-word "arg1"
    ? v2
]

>> f "goodbye"
V1 is a string of value: "goodbye"
** Script Error: arg1 has no value
** Where: f
** Near: v2: get to-lit-word "arg1"

如何使用“get”获取参数值?

2 个答案:

答案 0 :(得分:2)

对于初学者,我会提到当你在这样的FUNC中使用 v1 v2 时,你会将它们写入封闭的上下文中。所以它们就像“全局变量”。要取消您放入FUNC-spec func [arg1 /local v1 v2]

(注意:Rebol3有FUNCTION自动扫描本地人并为你构建底层FUNC。但是FUNCTION在Rebol2中意味着其他东西,因此可用作FUNCT。)


另外:当你写get 'a时,你没有通过一个点亮的词来获得。它们的亮点是让它们不被抬头的原因,但是当评估者在它上面运行时......一个点燃的词被评估为一个词:

>> type? 'a
== word!

如果确实想要将一个单词参数传递给函数,则必须引用它:

>> type? quote 'a
== lit-word!
显然,GET并没有拒绝你传递一个点燃字样的东西!虽然我认为如果它更加狭窄,它会更清楚。在任何情况下,我都会将其写为get to-word "a"


我可能是一个不好的人,试图回答你的主要问题。但我会指出,即使第一种模式在Rebol 3中也不起作用:

>> a: "hello"
== "hello"

>> get to-word "a"
** Script error: a word is not bound to a context
** Where: get
** Near: get to-word "a"

为了让GET能够从一个单词中找到一个值,仅仅“成为一个单词”是不够的。这个词必须绑定到一个充当“上下文”的对象;和绑定是附加到单词本身的属性。

Rebol 2与Rebol 3的行为略有不同。但是如果你想要一个充满信息的消息,那么主题就有一些帖子:

What is the summary of the differences in binding behaviour between Rebol 2 and 3?

我常常发现,如果我说to-word "some-string"而不是说load "some-string",我可以接受。所以在Rebol3:

>> a: "hello"
== "hello"

>> get load "a"
== "hello"

这些函数参数看起来是另一回事。您可以通过在该上下文中查询其他内容来手动将转换后的单词绑定到您获得的上下文:

f: func [arg1 /local dummy] [
    v2: get bind (to-word "arg1") (bind? 'dummy)
    ? v2
] 

>> f "goodbye"
V2 is a string of value "goodbye"

除非你使用闭包,否则它适用于Rebol2,但不适用于Rebol3:

f: closure [arg1 /local dummy] [
    v2: get bind (to-word "arg1") (bind? 'dummy)
    ? v2
] 

>> f "goodbye"
V2 is a string of value "goodbye"

在关于Rebol 的神秘陈述类别中(如“没有变量,冒号不是赋值运算符”)你可以添加“Rebol实际上根本没有范围界定。“

Is there a overall explanation about definitional scoping in Rebol and Red

您必须向专家询问有关聊天的详细信息......

答案 1 :(得分:1)

对于它的好处,这可以稍微短一些

>> f: func [ arg1] [
[    get bind to-word "arg1" 'arg1
[    ]
>> f "goodbye"
== "goodbye"
相关问题