Basics of AppleScript

Copy Command

The copy command works in a different way for Records and Lists. Let’s take a simple example first.

Script [8.5.1]:

set x to 10
set copyX to x -- stores copy of x i.e. 10
set x to 100
get copyX -- returns copy of x

Explanation: Here I created a variable x which stores 10. I created a copy of x i.e. copyX which stores value of x that is 10. Now I assign x with a new value of 100. However when I use get command to print value of copyX, 10 is printed in result tab. This is because I stored a COPY of x to copyX.

Figure 8.5.1

Figure 8.5.1 Copy of a Variable

Let’s take a look at how this works in Records (and Lists).

Script [8.5.2]:

set studentData to {myAge:18}
set copyStudentData to studentData
set myAge of studentData to 20
get copyStudentData

Explanation: In this case, I have created a record named studentData with a property myAge. I also created a copy of record studentData and stored it in copyStudentData.

Then I changed the value of myAge in studentData to 20. Finally when I used the get command to print copyStudentData, the new value 20 is printed. This is because, when I use get command, the copyStudentData checks for the new data in studentData.

Figure 8.5.2

Figure 8.5.2 Trying to Copy Records

If 3rd statement of Script 8.5.2 was,

set studentData to {myAge:20}

then output would be 18 and not 20. This is because when we use the get command, the new changes in the properties are returned and not new properties.

Figure 8.5.2-2

Figure 8.5.2-2 Copying Records

Script [8.5.3]:

set studentData to {myAge:18}
copy studentData to copyStudentData -- now a copy is stored
set myAge of studentData to 20
get copyStudentData

Explanation: Here I created a record named studentData and copied it to copyStudentData using copy command. On using copy command, a copy is created. So now if I change property values in original record, copyStudentData will still retain the values which were copied when copy command was used.

Figure 8.5.3

Figure 8.5.3 Copy Command

Copy command plays a vital role in script, when you try to debug the script. Because if we use the set command in lists and records, it will not store the copy. Rather it will store the latest changes.