Global variable?

I’m writing a project in applescript studio, and I can’t seem to grasp how global variables work. In my startup script, I have some code that sets a few global variables. It’s all great, until I try to access them from within another script that I use for checkboxes. The startup script is here:

on launched theObject
	set prefPaneNibLoaded to false
	global prefsLocation
	global prefsFile
	global monsters
	global animals
	global maxplayers
	global pvp
	global spawnprotection
	set prefsLocation to ""
	set prefsFile to ""
	set monsters to ""
	set animals to ""
	set maxplayers to ""
	set pvp to ""
	set spawnprotection to ""
end launched

and the checkbox one is here

on clicked theObject
	tell button "prefAnimals" of window 1
		if animals is "true" then
			set animals to "false"
		else
			set animals to "true"
		end if
	end tell
end clicked

These are in different windows, called by different objects. Anything i’m doing wrong? It just gives me a

Model: 10.6.3 customMac
Browser: RockMelt Beta
Operating System: Mac OS X (10.6)

Well you need to define a global in every script, this is normal for a programming language. With global you tell that that the variable is defined elsewhere (other line of code even through different script) and that the variable is a property of the script object. So if you want to take use a variable from another script object you need also the global definition again in your script you wanna use it.

The simplest solution is to put all of your code in a single file/document. Your global variable should work then.

If you need/want to have separate files, then a global variable is only global in the script file/document where you declare it. It is not “global” across your entire app. The best way to do that is to set up a variable in the plist file and read/write to that. Every page in your app can access the plist file.

Model: iMac Intel 10.5.8
Browser: Firefox 3.0.2
Operating System: Mac OS X (10.5)

Oh, thanks! The last language I used had cross-script variables, so I didn’t really know. How would I go about doing the plist thing you mentioned? I’m just learning file reading and writing.

My expierience is that matt’s solution is not done. You don’t define globals in files if you don’t need them in another process.

Let’s say the following script object is a file


--##main script file##--
property AGLOBAL : "Hello World!" --I use caps to make the difference between globals and locals

set childObject to load script file "path:to:file"
childObject's showGlobal() --show dialog; hello world
set AGLOBAL to "Goobye"
childObject's showGlobal() --show dialog; goodbye

in the other script file you have something like this


--##subscript##--
global AGLOBAL 

on showGlobal()
display dialog AGLOBAL
end showGlobal