tk3 (home, dev, source, bugs, help)

RPGCodeLanguage Features — Scope

Contents

Variable scope

Variable scope

In RPGCode, "scope" refers to a context in which your variables exist. For example, all variables declared in a program are considered global by default. When a variable is declared in the global scope, it will exist in memory until it is either unset (via the kill() function) or trans3 is closed. For example, look at this code:

function f()
{
	x = 1;
}

f();
show(x);
wait();

If you run this code in the program editor, you'll see that calling f() assigns 1 to the variable x and it can still be printed outside of the function. This is because it was declared in the global scope. However, if we declare it in the local scope, it will not be accessible outside of f(). In this example, trying to show x will print nothing:

function f()
{
	local(x);
	x = 1;
}

f();
show(x);
wait();

The variable x in the previous example is now local to the function f, so it can't be accessed anywhere else.

Using autolocal

You can set which scope is the default for newly created variables with the autoLocal() function. Since variables will default to local when autoLocal is switched on, they will automatically be deleted at the end of a program (or if they are declared in a function, when the function finishes executing). This can help keep your code cleaner and more succinct because you will not need to manually kill variables at the end of a script and you will not have any unnecessary variables hanging around after their use runs out.

// After this line of code, all (new) variables will be created locally.
autolocal(true);

// This variable will be deleted at the end of the program:
someVariable = 32;

// Switch back to global scope.
autolocal(false);

// This variable will only be deleted when the engine is closed
// or it is killed:
anotherVariable = 64;

Other uses

You can still create global variables when autoLocal is turned on by using global(). It is used in the same way that local() is used.

However, local() and global() are not only useful for creating variables in a specific scope: They can also refer to different variables of the same name in different scopes. This next example illustrates using two variables of the same name in different scopes:

function f()
{
	// Create a local variable with a value of 3.
	local(x) = 3;

	// Show the local variable "x".
	show(x);
	
	// Now, fetch the global variable "x".
	show(global(x));
	
	wait();
}

x = 9;
f();

When you run this example, the values 3 and then 9 should be printed to the screen.


previous, forward