在http://business-programming.com/business_programming.html#section-2.6上给出的示例中:
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: []呢?同样,是否应该对所有变量初始化都执行此操作,或者是否存在某些需要执行此操作的选择性类型?
编辑:我发现下面的代码运行正常:
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输出正常:
["Screwdriver" "Hammer" "Wrench"]
["1.99" "4.99" "5.99"]
["Screwdriver" "Hammer" "Wrench"]
["1.99" "4.99" "5.99"]但不是如下所示:
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这里的输出是重复的:
["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"]只有当初始化在函数中时才会出现问题吗?
显然,默认情况下,函数中的所有变量都被视为全局变量,并且只在开始时创建一次。该语言似乎正在将我的函数转换为:
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的多个调用的响应是可以理解的。在循环中创建的全局函数也只创建一次。
发布于 2017-10-01 12:55:28
在这个脚本中不需要copy [],因为当它再次运行时,之前对items和prices系列的所有引用都将重新创建。
但是,如果items: []可能会在同一脚本中多次运行,那么您需要进行复制,以确保每次都创建一个新的序列,而不仅仅是引用现有的序列。
https://stackoverflow.com/questions/46509262
复制相似问题