Sharing variable constants

I have set of script applications which together define an overall application. In other words, there is one main application which interacts with the user and spawns off several sub-applications (stay-open) which essentially run in the background until the main app is finished, then they are all told to quit.

I have a dozen or so constants I wish to share among the main script and all sub-scripts. In a former life, this was done for example with “header files” and #include statements. This allowed a set of variables/constants to be set in one file that could be included in all others that needed to use them. In other words, if any of these constants change, it would be more optimal to change them in one file instead of every script file.

For example:

– Shared Constants
set MainCity to “Boston”
set numCities to 10
set numRoads to 5
set numCars to 50
– end

I want to put these MainCity, numCities, etc. in one place to be shared by several scripts. Is that a “script library”? Or what?

How can this be done in AppleScript?

Maybe something like this?

-- constants.scpt
on getConstants()
	set constantsDictionary to {mainCity:"Boston", numCities:"10"}
	return constantsDictionary
end getConstants

Reading from another file:

set included to load script ("Macintosh HD:Users:kmitko:Desktop:constants.scpt" as alias)
tell included to set mainCity to (get mainCity of getConstants())
mainCity
1 Like

Nowadays you can do it with a Script Library

Save these lines as compiled script “MyConstants.scpt” in ~/Library/Script Libraries (~ represents your home folder)

property mainCity : "Boston"
property numCities : 10
property numRoads : 5
property numCars : 50

And access the values simply with

tell script "MyConstants"
	set theCity to its mainCity
	set numberOfCars to its numCars
end tell
3 Likes

StefanK’s example seemed a perfect solution. So I followed that but it fails. Compiled script library (in proper location) MyConstants says:

property ALL_Cities : 12

App says:

tell script “MyConstants”
set numCities to its ALL_Cities
end tell

When app is run, at set numCities causes:
—————
AppleScript Execution Error

Can’t make ALL_Cities into type reference.
—————

Seems straightforward and simple, but why does it fail?

Ok, I deleted “use scripting additions” from MyConstants and now the app runs through without error.