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

标签 rebol rebol2

这适用于外壳级别:

>> 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”获取参数值?

最佳答案

对于初学者,我会提到当您使用 v1 v2 在这样的 FUNC 中,您正在将它们写入封闭的上下文中。所以他们会表现得像“全局变量”。为了抑制您在 FUNC 规范中添加的内容 func [arg1 /local v1 v2] .

(注意:Rebol3 具有 FUNCTION,它会自动扫描本地变量并为您构建底层 FUNC。但 FUNCTION 在 Rebol2 中意味着其他东西,因此可以作为 FUNCT 使用。)

另外:当你写 get 'a你没有通过一个简单的词来获取。他们的 lit-ness 是让他们无法被查找的原因,但是当评估者运行它时......一个 lit-word 被评估为一个单词:

>> type? 'a
== word!

如果您真的想将 lit-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 能够从一个单词中找到一个值,仅仅“成为一个单词”是不够的。该词必须与充当“上下文”的某个对象绑定(bind);绑定(bind)是附加到单词本身的属性。

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"

这些函数参数看起来是一个不同的故事。您可以通过在该上下文中查询其他内容来手动将转换后的单词绑定(bind)到您获得的上下文:
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

您必须在聊天中向专家询问更多详细信息...

关于rebol - 在 Rebol 中以编程方式检索函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24946173/

相关文章:

webserver - 在哪里可以找到Rebol 3微型Web服务器?

object - 为什么在Rebol2中动态添加代码到对象不生效?

fastcgi - Rebol在FCGI设置中的缩放程度如何?

Rebol 或 Red 中的字符串搜索

Rebol 快速入门

rebol - 我如何加入 Rebol 中的 SSDP 多播组?

rebol - 将数据 block 数组写入文件

rebol - 如何设置按钮操作的样式

Windows 7 不提供 rebol View 作为文件打开器

function - 为什么在 REBOL 中函数 "have memory"?