Using Functions as Property values

I have stumbled on a trick which might or might not be a good thing - I’m hoping to get some advice from some more experienced scripters.

The idea of persistent properties fits what I need. By that I mean calculating a property value once, and it becomes “permanent”, at least until a re-compile.

I found that I can define a property to have a value that is the result of a function. For example, here’s some code that I’m playing with:

on GetMyAppFolder()
    tell application "Finder"
        set MyApp to application file id MyAppCreator -- MyApp is a file reference
        if exists MyApp then
            set MyAppPath to MyApp as alias as string -- get full path
            set I to length of MyAppPath
            repeat until character I of MyAppPath = ":"
                 set I to I-1 --- back up until colon found
            end repeat
            return (characters 1 through I of MyAppPath) as text
             error "Cannot find MyApp" number -1700
       end if
    end tell
end GetMyAppFolder

I haven’t timed it. It’s not a terribly long operation, but I’m trying to stay as unobtrusive as possible - this script will run in the background periodically.

The magic happens (for me) when I add one line, after the above:

property MyAppFolder: GetMyAppFolder()

What this means, I found out, is that the function is called ONCE after compiling, and the result is stored. Every time after that (until a re-compile), the stored result is regurgitated, which HAS to be a faster response.

I realize that if MyApp is moved, the script will not work correctly until it’s re-compiled, since the stored value is no longer correct. I think I can live with that in my situation.

I’m guessing that the property value is stored in a resource in the script app file since it survives even a reboot, therefore, the script app must be writable (not on a CD-ROM, for example).

Are there any other drawbacks that I’m not seeing? This will run on OS 9.x only.

What I do is create a property and set it to a null value and then each time the script is run, perform a test on the property and if it fails, then reload it if possible. This allows you to have the script be totally portable and get the benefits of calling the load routine only if necessary:


It’s a legitimate way of doing things if it suits your purposes. A few years ago, a scripter who called himself Richard23 used it to detect when a script was being recompiled! The handler that was called to set the property displayed a dialog that said something along the lines of “Naughty naughty!” :slight_smile:

The current values of all globals and properties belonging to a script are saved back into the script file every time it’s run. You’ll see this reflected in the file’s modification date.