Reputation: 24623
In example given on 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"
Why should one do items: copy []
and not items: []
? Also should this be done for all variable initializations or are there some selective types for which this is needed?
Edit: I find that following code works all right:
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
Output is ok:
["Screwdriver" "Hammer" "Wrench"]
["1.99" "4.99" "5.99"]
["Screwdriver" "Hammer" "Wrench"]
["1.99" "4.99" "5.99"]
But not following:
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
Output is duplicated here:
["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"]
Is the problem only when initialization is in a function?
Apparently, all variables in a function are taken as global variables by default and created only once at start. It seems that the language is converting my function to:
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" ]
Now the response of multiple calls to myfn is understandable. Global functions created in a loop are also created only once.
Upvotes: 1
Views: 122
Reputation: 4886
The copy []
is not needed in this script because when it's run again, all prior references to the series items
and prices
will be created anew.
But if there's a possibility that the items: []
is going to run more than once inside the same script, then you need to copy to make sure you create a new series each time, and not just reference the existing series.
Upvotes: 2