首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用Rebol/Red语言进行初始化

用Rebol/Red语言进行初始化
EN

Stack Overflow用户
提问于 2017-10-01 12:37:19
回答 1查看 89关注 0票数 1

http://business-programming.com/business_programming.html#section-2.6上给出的示例中:

代码语言:javascript
运行
复制
REBOL []
items: copy []               ; WHY NOT JUST "items: []"
prices: copy []              ; WHY NOT JUST "prices: []"
append items "Screwdriver"
append prices "1.99"
append items "Hammer"
append prices "4.99"
append items "Wrench"
append prices "5.99"

为什么要做items: copy []而不是items: []呢?同样,是否应该对所有变量初始化都执行此操作,或者是否存在某些需要执行此操作的选择性类型?

编辑:我发现下面的代码运行正常:

代码语言:javascript
运行
复制
REBOL []
items: []   
prices: []  
append items "Screwdriver"
append prices "1.99"
append items "Hammer"
append prices "4.99"
append items "Wrench"
append prices "5.99"

probe items
probe prices

items: []   
prices: []  
append items "Screwdriver"
append prices "1.99"
append items "Hammer"
append prices "4.99"
append items "Wrench"
append prices "5.99"

probe items
probe prices

输出正常:

代码语言:javascript
运行
复制
["Screwdriver" "Hammer" "Wrench"]
["1.99" "4.99" "5.99"]
["Screwdriver" "Hammer" "Wrench"]
["1.99" "4.99" "5.99"]

但不是如下所示:

代码语言:javascript
运行
复制
REBOL []

myfn: func [][
    items: []   
    prices: []  
    append items "Screwdriver"
    append prices "1.99"
    append items "Hammer"
    append prices "4.99"
    append items "Wrench"
    append prices "5.99" ]

do myfn
probe items
probe prices

do myfn
probe items
probe prices

这里的输出是重复的:

代码语言:javascript
运行
复制
["Screwdriver" "Hammer" "Wrench"]
["1.99" "4.99" "5.99"]
["Screwdriver" "Hammer" "Wrench" "Screwdriver" "Hammer" "Wrench"]
["1.99" "4.99" "5.99" "1.99" "4.99" "5.99"]

只有当初始化在函数中时才会出现问题吗?

显然,默认情况下,函数中的所有变量都被视为全局变量,并且只在开始时创建一次。该语言似乎正在将我的函数转换为:

代码语言:javascript
运行
复制
items: []   
prices: []  
myfn: func [][
    append items "Screwdriver"
    append prices "1.99"
    append items "Hammer"
    append prices "4.99"
    append items "Wrench"
    append prices "5.99" ]

现在对myfn的多个调用的响应是可以理解的。在循环中创建的全局函数也只创建一次。

EN

回答 1

Stack Overflow用户

发布于 2017-10-01 12:55:28

在这个脚本中不需要copy [],因为当它再次运行时,之前对itemsprices系列的所有引用都将重新创建。

但是,如果items: []可能会在同一脚本中多次运行,那么您需要进行复制,以确保每次都创建一个新的序列,而不仅仅是引用现有的序列。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46509262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档