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?
-- 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
I tested kmitko’s and Stefan’s solutions, and they work great. An alternative is a Plist, although it requires the Foundation framework. Another alternative is a text file, but that’s pretty straightforward.
--individual keys and values can be saved/retrieved instead of a list if that's preferred
--normally readPlist would be run before and separately from writePlist
use framework "Foundation"
use scripting additions
writePlist("theData", {"Boston", 10, 5, 50}) --the list parameter contains mainCity, numCities, numRoads, numCars
try
set {theCity, numCities, numRoads, numCars} to readPlist("theData")
on error --if Plist not found
set {theCity, numCities, numRoads, numCars} to {"", 0, 0, 0}
end try
return theCity --just a test
on readPlist(theKey)
set theDefaults to current application's NSUserDefaults's alloc()'s initWithSuiteName:"com.oxylos.Test"
return (theDefaults's objectForKey:theKey) as list
end readPlist
on writePlist(theKey, theValue)
set theDefaults to current application's NSUserDefaults's alloc()'s initWithSuiteName:"com.oxylos.Test"
theDefaults's setObject:theValue forKey:theKey
end writePlist