Mel - Maya Embedded Language

<HOME>   <PREVIOUS>   <NEXT>

Variable Scope

It is important understand the scope of variables. Variables are only seen within the braces that they reside { }, and their children. Braces are also known as blocks.
Take the following code as an example.

//the parent block
{
int $a = 5;
int $b = 2;
//the child block
     {
     int $c =6;
     print $b;
     }
print $a;
print $c;
}
  • Children are aware of variables in the parent block but Parents are not aware of variables in the Child block. Just remember that parents don typically know what their kids do.
  • Variable $a will print a value of 5 because the print command is in the scope of variable $a.
    When print $c is reached we recieve an error because variable $c was initialized in a different block. Variable $b was able to print because the print command resided in a child block and it knew what was declared in the parent block.

    What if we, the user, want a variable or procedure that can be seen by any given MEL script after its initilization? This is where global and local variables come into play. Prior to this point we have been using local variables and proceedures. If we want a variable or procedure to be global we must specify this at creation time.

    Global Variables
    To initialize a global variable you must declare it at the top most block structure of your code. You will need to re-initalize it in any blocks that you want to use it in. If you fail to do this, the block structure will assume the variable is a new local variable and not associate it with the global variable.
    {
    global string $myGlobalString;
         {
         global string $myGlobalString = "Oh, I get it";
         print $myGlobalString;
         }
    }
    When you declare a global variable and it already exists, it will use the values in the old variable instead of creating a new empty one.
    Global Procedures
    Global Procedures are not much different than global variables. Once declared they are visible throughout Maya.
    {
    global proc float myGlobalProc(float $myInput)
         {
         float $myNewValue = $myInput * 3.25;
         return $myNewValue;
         }
    }
    Type this in and hit enter. This will initialize our global procedure.

    To call it, type:
    int $myNum = myGlobalProc(2.5);
    print $myNum;
    This is a global proc that returns a value. To make it a global procedure that does not return a value simply write the procedure as follows:
    {
    global proc myGlobalProc2(float $myInput)
         {
         float $myNewValue = $myInput * 3.25;
         print $myNewValue;
         }
    }
    To call it, type:
    myGlobalProc2(9.7);

    <Top>