在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的响应是可以理解的。 在循环中创建的全局函数也只创建一次。
答案 0 :(得分:2)
此脚本中不需要copy []
,因为当它再次运行时,系列items
和prices
的所有先前引用都将重新创建。
但如果items: []
可能会在同一个脚本中运行多次,那么您需要复制以确保每次都创建一个新系列,而不仅仅是引用现有的系列。