Home   Archive   Permalink



Refining my understanding of 'copy'

I still am not totally clear about when to use the 'copy' function. In the following sample, I call a function that returns a string, and I want to save that string for future use. I do that operation with, and without, a 'copy' and get the same result. Are my results really the same, or is there something else behind the scenes that makes them actually different even if they look the same?
    
Thank you. Sample follows, and results follow that.
    
R E B O L [
]
    
GLB-SUBSTRING: func [
     'Return a substring from the start position to the end position'
     INPUT-STRING [series!] 'Full input string'
     START-POS    [number!] 'Starting position of substring'
     END-POS     [number!] 'Ending position of substring'
] [
     if END-POS = -1 [END-POS: length? INPUT-STRING]
     return skip (copy/part INPUT-STRING END-POS) (START-POS - 1)
]
    
TESTSTRING: 'AAAAAAAAAABBBBBBBBBB'
SUB1: copy ''
SUB2: copy ''
    
;; Which way is right, or doesn't it matter in this situation?
SUB1: GLB-SUBSTRING TESTSTRING 1 10         ;; no 'copy'
SUB2: copy GLB-SUBSTRING TESTSTRING 11 20 ;; with 'copy'
    
print rejoin ['SUB1 = '' SUB1 ''']
print rejoin ['SUB2 = '' SUB2 ''']
    
halt
    
Result:
    
SUB1 = 'AAAAAAAAAA'
SUB2 = 'BBBBBBBBBB'
>>
    


posted by:   Steven White     14-Jan-2016/12:08:59-8:00



Generally, use 'copy to ensure that any data you manipulate isn't unintentionally changed elsewhere, where a reference to it still exists.
    
Your function above uses copy/part, so you're using a copy of the input string in both example cases.
    
You'll notice the need for 'copy most in situations like this:
    
R E B O L []
view layout [
     f: field [append t/data f/text show t]
     t: text-list
]
    
In that example, every time a value is added to the text-list widget, Rebol keeps track of the original reference to f/text, so each time that value is changed, the value displayed in the text-list is updated. To make that example work as expected, you can use a *copy* of the value in the f/text widget, when it's added to the text-list, so only that unique and separately copied value is ever displayed, regardless of what value is currently displayed in the 'f field.
    
R E B O L []
view layout [
     f: field [append t/data COPY f/text show t]
     t: text-list
]

posted by:   Nick     16-Jan-2016/0:15:05-8:00



I tried to answer this yesterday but I received an error page. You use copy to make sure you have a new string/series and not only a pointer to the existing string.

posted by:   iArnold     16-Jan-2016/11:44:45-8:00