Interestingly, if you put these inside a function, that makes their scope just that function. If you put them outside any function, then they're local/global for all the functions defined in that script area. The 'global' at script level is obvious, IMHO, but the 'local' at script level is something like declaring a 'static' variable inside a 'C' file; all the functions in that file see it, but no functions outside that file see it.
to declare a variable inside a handler with local myVar is a way to ensure that it is declared if you use 'Strict Compilation Mode' that you can turn on in the Preferences -> Script Editor. If you don't declare it first and try to use variables on the fly in strict compilation mode the Script Editor will throw an error.
If you do not use the strict compilation mode you don't have to declare a variable inside a handler, it is optional.
If you declare a variable with local sVar outside of a handler the scope of that variable is all handlers inside that script:
This type of variable is referred to as a 'script local variable'. This is different from a local or a global variable.
Code: Select all
local sVar
on something
put "xyz" into sVar
end something
on somethingElse
answer sVar
end somethingElse
as for global variables you have to declare them, but you can declare them inside a handler for use in that handler or outside of all handlers of a script to be accessible for all handlers in that script.
Code: Select all
global gVar
on something
put "xyz" into gVar
end something
on somethingElse
answer gVar
end somethingElse
or
Code: Select all
on something
global gVar
put "xyz" into gVar
end something
on somethingElse
global gVar
answer gVar
end somethingElse
Many people here have adapted the habit to prepend the variables with a letter depending on what type of variables they are:
t (like in temp) for local variables
s (like in script local) for script local variables
g (like in global) for global variables
The beauty of script local variables is that they persist. And that their scope is restricted to the script. Global variables also persist but are accessible from every open stack. That can lead to confusion if you're not careful with the naming etc. I prefer to store stuff that can be accessed from every handler in custom properties.
I hope this helps a little to sort this out.
Kind regards
Bernd