![]()
Global and local variables
- Variables you define outside of procedures are visible (able to be accessed and changed) to all other top level MEL code.
- Variables you define inside a procedure are only visible within that procedure. These variables are called local variables. For example:
Variables that are local to a procedure are separate from global variables and separate from variables in other procedures. A local variable will override a global variable with the same name within the procedure.
All this allows you to write procedures without worrying whether the variable names you choose will conflict with Maya or other procedures.
- You can make variables inside a procedure visible globally using the
globalkeyword.If you want to create and maintain a variable in one procedure and also use it outside of that procedure, you can declare it as a global variable. For example:
The $counter variable can be read or changed by any MEL code at the top level, and in other procedures that also declare $counter to be global. Also, if a global $counter variable already exists, this procedure will use it instead of creating a new variable.
For example, the following code uses the $globalText global variable in the myProcedure procedure; the globalText global variable was defined outside of procedures.:
global string $globalText; global proc myProcedure() { global string $globalText; print($globalText); }In general it is good programming practice to avoid using global variables whenever possible. This makes it less likely that calling a procedure will have unwanted side effects.