swordmaster by swordmaster May 30, 2017
Tutorial

Using Global Variables

Sometimes we want to be able to share the state of something in game across programs. A good example would be a custom inventory or progression system, we want to be able to keep track of this kind of information in a permanent way. Up until this point any variables you declared in your programs ceased to exist after a program ended, they were local to your program, Another type of variable we can use in the engine is the global variable, these can be accessed across programs until they are explictly removed. They can be used to hold all sorts of things: booleans, strings, objects, functions, etc. Global variables can be created and accessed using the unique string associated with them with calls to rpgcode.setGlobal and rpgcode.getGlobal:


// Reference to the global name, saves on typos!
var swordActive = "swordActive";

// Set the global variable "swordActive" to the boolean value of false.
rpgcode.setGlobal(swordActive, false);

// Read the value of the global we just set.
var isSwordActive = rpgcode.getGlobal("swordActive");

// Set the global variable "swordActive" to the boolean value of true.
rpgcode.setGlobal(swordActive, true);

                                

A more complete example of how global variables can be used in a game:


/*
 * Example of how to retrieve and set the state of a user defined
 * global variable.
 */

// Game assets used in this program
var assets = {
    "images": [
        "mwin_small.png",
        "sword_profile_1_small.png",
    ]
};

// Reference to the global name, saves on typos!
var swordActive = "swordActive";

// Load up the assets we need for this program.
rpgcode.loadAssets(assets, function() {
   // Set the dialog box background image, and profile picture.
   rpgcode.setDialogGraphics("sword_profile_1_small.png", "mwin_small.png");

   // Set the global variable "swordActive" to the boolean value of false.
   rpgcode.setGlobal(swordActive, false);

   // Read the value of the global we just set.
   var isSwordActive = rpgcode.getGlobal("swordActive");

   // This will always be false.
   if (isSwordActive === false) {
      rpgcode.showDialog("You do not have the sword yet!");

      // Wait 3 seconds then change the value.
      rpgcode.delay(3000, function() {
         // Set the global variable "swordActive" to the boolean value of true.
         rpgcode.setGlobal(swordActive, true);

         // Read the updated value of the global.
         isSwordActive = rpgcode.getGlobal(swordActive);

         // This will always be true.
         if (isSwordActive === true) {
            rpgcode.showDialog("You have the sword now!");
         }

         rpgcode.delay(3000, function() {
            rpgcode.clearDialog();
            rpgcode.endProgram();
         });
      });
   }
});