Monday, December 11, 2017

#1 2005-10-13 02:49:49 pm

julifos
Administrator
From:: Malasaña, Madrid
Registered: 2002-11-20
Posts: 2014

What is a "local"?

A local is a variable available only to the current handler.

Applescript:

set x to 5
display dialog x
tellMeAboutX()

to tellMeAboutX()
   display dialog x
end tellMeAboutX

As you see if you run this sample, you get a dialog which says "5". But you will receive an error when trying to do the same within the "tellMeAboutX" handler, since the variable "x" is only accessible to the handler which declared such variable (the main handler, an implicit "run" handler).

You can declare local variables, as you do with globals, but it is not mandatory, and most of scripters who do it, do it for better organization purposes or to avoid data being saved under some circumstances.

Applescript:

local myName, myAge, myPhoneNumber

set myName to text returned of (display dialog "What is your name?" default answer "")
set myAge to text returned of (display dialog "How old are your?" default answer "")
set myPhoneNumber to text returned of (display dialog "What is your phone number?" default answer "")

display dialog "The text for your advertisement is done!" default answer "Hello! My name is " & myName & " and I'm " & myAge & " years old." & return & "Do you wanna meet me? (I'm so sweet)" & return & "Call me today: " & myPhoneNumber & "!!!"

About "avoid data being saved". Let's go to the examples, so you understand what's going on. Save this code as application:

Applescript:

set x to current date
display dialog "It's now " & (time string of x)

Take a look to the modification date of your app (if you saved as application-bundle, you will look better at "/Contents/Resources/Scripts/main.scpt", inside the bundle). Run the app (double-click it!).

Check the modification date again. It changed? Yes (at least, it should). This means that some kind of info is stored in your un-declared variable "x", after the script is run, before quitting.

Now, add the line "local x" at the beginning of the same script, and test it again... Yes! Now, the modification date hasn't changed. No changes are saved, and the script isn't modified (credits go to the "local" declaration).

So, declaring variables as "local" is useful, for example, when you run this script from a CD. In this situation, the system can't write data to the script, and it will throw an error such as "couldn't save changes because you have not write permission".

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)