Friday, February 23, 2018

You are not logged in.

#1 2005-10-13 02:05:30 pm

julifos
Registered: 2002-11-20
Posts: 2014

What is a "variable"?

This is a very basic concept in all programming languages, as well as other disciplines, as maths or statistics.

A variable is like a box where your put your shoes, named "box of shoes". When you need again your shoes, you scream "box of shoes!!!" and the box of shoes will spit your shoes back to you.

Applescript:

tell application "Finder"
set myVariable to count items of desktop
end tell

display dialog "There are currently " & myVariable & " items at desktop!"

In this example, we enclose a number into the variable named "myVariable", and we can use such number again when we need it (eg, displaying a dialog).

There are two different syntaxes to define a variable in AppleScript:

Applescript:

set myVariable to 5
copy 5 to myVariable

The most commonly used syntax is "set... to...", since you can get confused with other terminologies used by some apps, such as the Finder, which owns a command called "copy".

However, under some special circumstances, you must use "copy", which will create a real "copy" of the related value. Let's see this example:

Applescript:

set x to {1, 2, 3}
set y to x

set y's item 2 to "kaka"
x

Here, we create a variable called "x" whose value is "{1, 2, 3}" (a list of numbers). If we use the "set... to..." syntax, we are creating a duplicate list in the variable "y", linked directly to the variable "x". So, when we modify the value of "y", we are also modifying the original "x". If you see the result of running this script, you will see that the value of "x" is also the value of "y", instead of the original one.

If you use instead the "copy... to..." syntax, you will create an independent copy of the current "value of x"; and the variable "y" will be detached from "x", so "x" keeps allways its original value.

This applies only to variables whose contents are accessible by "index" or "label", which are currently lists and records.

Filed under: Finder

Offline