Variable Scope

<< Click to Display Table of Contents >>

Manual > Script Guide > Script Ver2 (SC2 syntax) >

Variable Scope

What is a scope?

Scope refers to the range within which a variable is valid. Where you declare a variable in a script determines its scope.

 

Broadly speaking, scope can be divided into whether the target variable is within a range enclosed in brackets ("{" and "}") or not; this determines whether the variable can be accessed from script code (in scope) or not (out of scope).

 

Here, variables defined within a blanket are called "local variables".

Also, variables defined outside the scope of a blanket, that is, outside of any function or event, are called "global variables."

 

 

About local variables

A local variable is a variable declared within an event or user-defined function, and is only available within the scope enclosed in brackets ("{" and "}").

 

In the following case, the variable "a" is executed in the OnInitialize event, and when the event ends, "a" will no longer exist. Therefore, it is not possible to set or retrieve a value for "a" from an external object.

 

event OnInitialize()
{
	var a = "Hello"; 
}

 

In the following example, the variable "b" is declared inside the if statement. In this case, the scope is only inside the if statement, and "b" does not exist outside the if statement.

Therefore, a reference error will occur if it is outside the scope, even if it is within the same event.

 

event OnInitialize()
{
	var a;

	if (a == 1)
	{
		var b = 123;
		b = b + 1; // Valid
	}

	b = b + 5; // Error
}

 

As in the above example, variables declared within a scope are only valid within that scope. Also, you cannot declare duplicate variable names within a single scope.

 

 

hint

For more information about if statements, see "Conditional Branching/Repetition (Statement)".

 

 

About Global Variables

A variable declared outside of an event or user-defined function blanket is a global variable, which means it can be commonly accessed by multiple events and functions.

 

Example 1) Example of declaring a global variable in a script of Script Ver2 action

 

var a; // Declaration of a global variable

event OnInitialize()
{
a = 1;
}

 

Global variables can be commonly accessed by functions and events.

 

Example 2) Accessing the global variable in Example 1 above

 

var a;

event OnInitialize()
{
	a = 1;
}

event OnHeartBeat()
{
	a = a + 1;
}