在 REBOL 中动态添加单词到上下文
想象一下以下 REBOL 代码:
foo: context [bar: 3]
我现在有一个上下文 foo
,其中定义了 'bar
。 如何动态地将新单词注入到此上下文中? 是否可以?
我已经尝试过:
set/any in foo 'baz 3
但这不起作用,因为 foo 'baz 中的表达式失败,因为 foo
中没有定义单词 'baz
> 上下文。
我应该补充一点,我意识到执行此操作的一种方法如下:
foo-prototype: [bar: 3] foo: context foo-prototype foo: context head append foo-prototype [baz: 3]
但是如果您无权访问 foo 的原型块怎么办?
Imagine the following REBOL code:
foo: context [bar: 3]
I now have a context foo
in which 'bar
is defined. How can I dynamically inject a new word into this context? Is it possible?
I've tried:
set/any in foo 'baz 3
But that doesn't work because the expression in foo 'baz
fails because there is no word 'baz
defined in the foo
context.
I should add that I realize one way to do this is as follows:
foo-prototype: [bar: 3] foo: context foo-prototype foo: context head append foo-prototype [baz: 3]
But what if you don't have access to foo
's prototype block?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过使用现有对象作为原型来创建新对象来实现相同的目的。
You can achieve the same by using the existing object as a prototype to create a new object.
有多种方法可以解决 REBOL/2 中无法扩展对象上下文这一事实。
也许您可以只使用 BLOCK!s 而不是 OBJECT!s:
您甚至可以通过仅附加对象本身来使“self 工作”:
但是当您要求扩展 OBJECT!s 时,您可能会去Peter WA Wood 的解决方案是简单地克隆对象。 请记住,通过这种方法,生成的克隆实际上与原始对象不同。
因此,如果在克隆/扩展之前已将某个单词设置为保存对象,则在克隆对象后,该单词仍将保存未扩展的对象:
如果您必须保持对对象的“引用”完整,您可能需要将需要扩展的对象包装在外部对象中,如图所示,
然后您可以在保留的同时安全地扩展对象,前提是您只存储对容器的引用。
顺便说一句,REBOL/3 将允许向 OBJECT! 中添加单词。
There are several ways to work around the fact that in REBOL/2 it's just not posssible to extend object contexts.
Probably you can just use BLOCK!s instead of OBJECT!s:
You can even make 'self working by just appending the object itself:
But as you've asked for extending OBJECT!s, you may go for Peter W A Wood's solution to simply clone the object. Just keep in mind that with this approach the resulting clone really is a different thing than the original object.
So, if some word has been set to hold the object prior to cloning/extending, after cloning the object that word will still hold the unextended object:
In case it's essential for you to keep "references" to the object intact, you might want to wrap the object you need to extend in an outer object as in
You can then safley extend the object while keeping, given you only store references to the container.
REBOL/3, btw, will allow adding words to OBJECT!s.
REBOL/Core 用户指南中说:
“许多块包含其他块和字符串。当这样的块被复制时,它的
子系列不被复制。 子系列直接引用,都是一样的
系列数据作为原始块。”
Said in REBOL/Core User Guide:
"Many blocks contain other blocks and strings. When such a block is copied, its
sub-series are not copied. The sub-series are referred to directly and are the same
series data as the original block."