Scope

From Director Online Wiki
Jump to: navigation, search

In programming languages the range where you can directly access variables and methods is called the scope.

Scope of a variable

In the Director Scripting Languages the scope of a variable is per default only the method in which you create it.

Example

In a script you define these two methods:

 on setVar(me)
   variableTest = 10
   me.incrementVar()
   put variableTest
 end setVar
 on incrementVar(me)
   variableTest = variableTest + 1
   put variableTest
 end incrementVar

This would give you the following output:

 -- 1
 -- 10

Although the variable in both handlers has the same name, each is limited to the scope of its own handler. When the incrementVar() handler is called, the variable variableTest within that handler starts off with a value of VOID. Changes to its value within the incrementVar() handler have no effect on the variable with the same name in the setVar() handler.

You can either pass the variable over to putVar or you can change the scope. Put the following on top of the same script:

 property variableTest

Declaring the variable as property widens the scope of it to the whole script. Now putVar can directly access it.

You can also make the variable global by putting this atop of the script:

 global variableTest

This makes the variable global, so it is not only accessible in this script, but rather in all scripts. You just have to declare it above the scripts where you want to use the specific variable.

Methods also have a scope - their range is always only the script. The exception is the Movie Script. Methods of Movie Scripts are globally accessible.

Note that these scopes only describe the direct access. Indirect access is possible beyond the scope (via passing of variables or access through instances).

Scope of an event

If you are working with Movies In A Window (MIAWs) or Linked Director Movies (LDMs) then you have to take into account the fact that an event, such as mouseUp or enterFrame occurs within the scope of a particular movie. For example, if you have two or more overlapping windows, mouse events are only sent to the uppermost window.

To direct an event to a movie in a different location (window or sprite), you can use the tell? command:

tell window("Help") to updateStage
tell sprite("LDM")
  sendSprite(1, #customEvent)
end tell

Scope of an object

Similarly, each movie, whether on the Stage, in a MIAW or in an LDM has its own actorList and timeOutList. Any events initiated by an object on the actorList or the timeOutList will be delivered within the scope of the current location.

It is possible (for instance) to place an object belonging to window A on the actorList of window B. If this object were to issue a #sendAllSprites event, it would be sent to all the sprites of window B.