Static Variables

From Director Online Wiki
Jump to: navigation, search

A static variable is one that is not removed from memory after creation, even when it goes out of scope. The concept is very similar to that of a global variable, except that while a global variable is accessible from anywhere, a static variable is only accessible within certain parts of the program code.

A static variable should not be confused with a constant. A constant is a named value that never changes, such as PI or RETURN. The name "static" does not imply that the value of the variable cannot change, it simply means that the variable has a fixed (or "static") memory location. This contrasts with the more common Local Variable, which is allocated temporary space on the stack, only for the duration of a particular handler.

Lingo has limited support for static variables, via script members. Each script member holds a static copy of all the properties for that script, which you can access like so:

    theValue = script( "my static variable script" ).myStaticVariable
    script( "my static variable script" ).myStaticVariable = theValue + 1

This copy of the properties is local to the current movie. It is completely separate from the copy of the properties that exists in each instance of the script (an instance is an object created with new).

The scope of these static variables is slightly different to Global Variables. Global variables are shared throughout the entire project. Static variables are local to the current movie. A MIAW or LDM has its own movie and therefore its own set of static variables.

This can be a very useful attribute if you want to share a variable between all the scripts in a particular movie, but have a different copy of the variable in every other movie in your project.

For example, you might have a collection of LDMs or MIAWs, each having the variables "windowName" and "windowLoc". Global variables would not suffice, because you can only have one copy of the same global variable for the entire project. Static variables are one possible solution to this problem.

See Static Scripts for sample code and a downloadable demonstration.