Don't click here unless you want to be banned.

LSL Wiki : GlobalVariable

HomePage :: PageIndex :: RecentChanges :: RecentlyCommented :: UserSettings :: You are ia360925.us.archive.org

Global Variable

A global variable is a variable declared before the default state declaration of a script; it has a global scope. These variables are accessible everywhere in the script, and anything can set them. However, they are not accessible outside of the script, in other scripts.

It is good coding practice to prefix global variables with a "g". Since LSL doesn't allow defining constants, variables can be used as pseudo-constants, usually with names that are all UPPERCASE. Just remember never to change their value anywhere else in the script.

Note: in global variable declarations, the initial values can not be expressions; they can either be a constant, another global variable, or a literal value (like the number 3).

Example:
// Stuff you can do:

integer gMyInteger = 3; // Valid declaration of a global variable.
integer gAnotherInteger = CHANGED_INVENTORY; // Valid declaration of a global variable.
integer gCopiedInteger = gAnotherInteger; // Valid declaration of a global variable.

integer CHAT_CHANNEL = 0; // Valid declaration of a pseudo-constant.

// Stuff you **can't** do:

string gAnotherIntegerAsString = (string)gAnotherInteger;
// ^^^^ ILLEGAL! Global variable declarations are not evaluated. (You can't typecast here.)

float gMyFloat = llFabs(482.334);
// ^^^^ ILLEGAL! Global variable declarations are not evaluated. (You can't call a function here.)

string gMyString = "Hello!" + "Goodbye!";
// ^^^^ ILLEGAL! Global variable declarations are not evaluated. (You can't use operators here.)

// Global functions:

myFunction() {
    gMyInteger = 45; // Valid.
}

integer anotherFunction () {
    return gMyInteger; // Valid.
}

default {
    state_entry() {
        gMyFloat = llFabs(482.334); // Valid.
        gMyInteger = 12; // Valid.
    }
}

state foo {
    touch_start(integer n) {
        llSay(CHAT_CHANNEL, "Touched.");
        gMyInteger = n; // Valid.

        CHAT_CHANNEL = 4; 
        // ^^^^ BAD CODING PRACTICE! Changing the value of a pseudo-constant is legal, since LSL doesnt 
        // have user-defined constants, but you will go to hell for this - after some very nasty debugging
    }
}

Global variables should be used with some care - see http://c2.com/cgi/wiki?GlobalVariablesAreBad. If you are tight on memory one technique is to store all your local variables in globals and then reduce the number of globals to the number of unique variables you actualy need; turning your global variables into registers. Of course, unless your really careful and have omni presence over your code; debugging will be maddening. Insanity will not be far behind.

Compare with local variables.


Tutorials | Variable
Comments [Hide comments/form]