Introduction to MEL and Variables

From TOI-Pedia


Introduction

This tutorial is an introduction into one of the scripting languages in Maya: MEL - Maya Embedded Language. This tutorial covers:

This tutorial uses a pavilion as an example to exercise the topics covered in this tutorial. At the end of the tutorial you can finish the pavilion to check the knowledge you obtained.

The Script Editor

You can enter commands in Maya in the Script editor. You can open the Script Editor through Window > General Editors > Script Editor. This interface is used to enter commands and scripts, but the history panel also provides feedback.

Maya scripteditor.jpg

If the Script Editor is opened, you'll see a window similar to the image above. The windows is divided into two parts: The top part is the history, the bottom part is where you can type. The history probably already contains some output. You'll notice that most actions in Maya result in output in the history panel. It shows the commands that are being executed and the results of those commands.

If make a polygon cube for example, we'll see something like this:

polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -tx 1 -ch 1;
// Result: pCube1 polyCube1 //

The first line is the command being executed. It shows the name of the command and several options, called flags for that command. You can recognize a flag by the dash (-) prefix, followed by one or more values.

The second line is the result of the commands. In this case it shows the name of the cube that has been created.


However, the functionality of the built-in Script Editor in Maya is limited. As soon as your scripts gets a little more complex, it's recommended to use a different editor. (The script editor in Maya 8.5 is improved dramatically, but still an external editor can be nice). One of the possibilities is Crimson Editor. If you save your file with the .mel extension, Crimson will understand it's a MEL-script and will 'color code' your script to improve readability, for instance: commands and variables get their own color. The extension .mel isn't in the standard list of file types when you save a file in Crimson. You need to suffix (type) .mel yourself.

You can use Copy-Paste to get your script from Crimson to the Script Editor van Maya to execute it, or you can save it in Crimson first (always a good idea) and the use File > Open Script in the Script Editor.

MEL Commands

You can enter MEL commands in the Script Editor. If you want to execute your command (or commands), you need to press Ctrl + enter (or the enter of your numpad). When you just press enter without ctrl, the cursor will jump to a new line.

Exercise:

Let's take a look at some commands: Open the Script Editor. To clear the History in the top panel, press the Maya Script Editor-Clear history.jpg button (or select Edit > Clear History), so we have some overview.

Now make a polygon cube the normal way: Create > Polygon Primitives > Cube (Make sure you disable Interactive creation in the Polygon Primitives menu first). You should see the corresponding command that is executed appear in the history.

Maya MEL-Create cube command in history panel.jpg

The history shows you the command that was executed - polyCube - and directly beneath the result of that command - in this case the name of the object that was created pCube1. Note that the result line starts with //. Later on we will see that this denotes a comment.


A script really is just a list of commands which are executed one by one (from top to bottom) once you execute the script (Ctrl + enter). In a bit you'll see various ways to influence which commands in your script are executed (which should be skipped or repeated).


Command reference

The list of commands may seem endless at first and the number of options for each command is even longer. It's madness to know each and every one by heart and it's completely useless to try. The Maya help contains a complete Command Reference, which describes every command and the flags for that command. You can open the Command Reference directly through the Help menu: Help > MEL Command Reference.

Exercise:

Let's go back to our polyCube example. Directly after the command you see some more text:

polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -tx 1 -ch 1;

These are the options for the command. They determine the behavior of the command, such as the size of the cube that is created in this example. A command can have zero or more options, each specified by a name prefixed by a dash. The first option in this example is the -w option. The Command Reference learns us that this specifies the width of the cube.

Now try some other actions in Maya, such as the creation of other geometry, moving and scaling objects, selecting objects, the create polygon tool, etc and see which commands are executed. Find the commands in the Command Reference and try to determine the purpose of some of the options.

Most of the commands have pretty sensible default values for most of the options. The default values are documented in the Command Reference. If the default value is ok, you don't need to specify it. This is useful when we start using the commands in our own script; it saves you a lot of typing.

Exercise:

Let's try to create a cube by typing the command ourselves and move it around. You may start with a new, empty scene, at this point.

Position your cursor in the bottom part of the Script Editor, the Input field, and enter the following command:

polyCube;

MEL tutorial polycube.jpg

Note that MEL is case sensitive, so you need to enter the command with a capital C in polyCube. When you press Ctrl + enter the command is executed. A default cube should be created and the command disappears from the input field. Note that this cube gets automatically selected.

Now try to move the selected object:

move -r 0 4 -2.6;

MEL tutorial move.jpg

Your cube should be moved. The option -r denotes a relative translation (see Command Reference). The object is in this case translated by: 4 units in the y and -2,6 in z. There is no translation in x. An absolute translation would move the pivot point of the object to the specified coordinates.

Try to move the cube relatively and absolutely yourself and try to scale and rotate it...


Syntax

Computers aren't too smart. They need very strict rules in order to understand the commands in your script. Therefore some rules should be applied when writing a script. Those rules are called syntax. You can compare it to the grammar of a language.

  • everything is case sensitive. The command polycube won't work, polyCube will
  • Each command is terminated by a ; at the end of the line (after the flags, if applicable). Only if you enter just a single command, you may omit the semicolon , but that is not recommended.
  • Comments (which shouldn't be executed) are preceded by // and end at the end of the line.
  • Large blocks of comments (multiple lines) are placed between /* [comment] */

Especially when your script is getting more complex or very long, it's of vital importance to use comments. It helps you (and others) to keep an overview and it makes it easier to understand your script if you use it at any later date. It helps you to understand the structure and find out how the script works.

Errors

By default, Maya doesn't tell you in which line number the error occurs. You can enable this by History > Line numbers in errors. Very useful.

Common causes for (syntax) errors:

Cannot find procedure "name"
Maya doesn't know this command. Probably you made a typo; note that everything is case sensitive.
Syntax Error
There is a serious problem with the syntax. Probably you forgot a semicolon (;), or bracket somewhere. The cause of the error doesn't need to be in the line number Maya reports (it reports the line where it detects a problem). Often the problem is in the line before the line where the error occurs.
Invalid flag
-name: The option (flag) you specified is not recognized.
Invalid argument
The value(s) you specified for one or more of the options of the command are invalid. This can happen when you forget to specify a value of when you specify the wrong type of value (text instead of a number, for example).


You can find more information on MEL errors in MEL Troubleshooting.

Variables

If you enter all commands with all values (numbers, sizes, etc) manually, a script isn't really too useful. It's very likely that the 'normal' interface will prove to be faster or at least more convenient. Scripting gets powerful when you use variables.

You may know variables (x, y, t) from math; variables are labels that refer to a value that may not be known at a given time. They correspond to a value (at the time of execution). A variable has three key properties:

  • a variable has a name
  • a variable has a value
  • a variable has a type

Variable names start with a $ to denote a variable. Variable names may not contain spaces, points or any special character. They can't begin with a number either.

example: $height (variable with the name height)

A variable can be assigned a value:

$height = 6.2;

Once that command has been executed, the variable $height has a value of 6.2. The computer will keep this value for height in memory until you assign a new value (or you shutdown Maya).

This variable can now be used in any command, for example:

polyCube -h $height;

This will create a cube. As soon as the command is executed, Maya will read the value of $height from memory and use that in this command. If this example is executed directly after the previous example, the value will be 6.2.

Exercise:

Take a look at the example below and analyze what happens when each line is executed in order:

$height = 6.2;
polyCube -h $height;
$height = 4;
polyCube -h $height;
MEL tutorial variable value1.jpg

All in all not too exciting yet, but we're getting there. This is the first step in writing more complex (and useful) scripts.

Types

There are a few types of variables. The type of a variable determines what kind of values can be stored. The most important types are:

float
numbers with a decimal precision
integer (int)
numbers without decimals
string
text
vector
vectors (we won't use them for now)

As soon as a variable is created and is set to a specific type, it can only store values of that type. If you try to assign a value of a different type, you may get an error or warning or you can get strange results. Only assigning a integer number to a float variable will work without errors; if you assign a decimal number to a variable with type int, all decimals will be ignored.

You cannot change the type of a variable. You need to restart Maya to start with a clean slate.

Declaring variables

To prevent any confusion or errors from occurring related to the type of a variable, it is recommended to declare a variable on first use. This will look something like this:

int $integer_number; float $name_of_my_var;

Declaring a variable should be done once for each variable in each script. To keep track of the variables you've used (declared) so far, it's recommended to place them all at the top of your script. Use comments to describe the use of variables.

You can declare a variable and assign it a value in one go:

int $number = 4; float $length = 25.3; string $text = "a piece of text";

Using variables in calculations

You can do calculations with your variables where you apply them. The calculation will be done and the result is used in the command.

Exercise:

Create a new, empty scene. Enter the following script in the script editor

float $gridsize = 0.3;
polyCube -w (4*$gridsize);
polyCube -w (6*$gridsize);
If you've got this working, adapt the script to make two cubes: one with a width of 2 times the gridsize, a height of half a gridsize and en depth of 6 times the gridsize. The other cube should have a width of 2 times the gridsize + 2, a height of 5 and a depth of gridsize to the power of two. The variable gridsize should have a value of 2.2. If that works (make sure you copy your script before executing), change the variable gridsize to 0.5 to see if it still works.

Notice the round brackets around the calculation (4 * $gridsize). The are compulsory to ensure that Maya will first determine the result of the calculation 'value of $gridsize times four' and then use the result of that calculation in the command (polyCube).

printing variable values

...

Control structures

Before was mentioned that a script, a list of commands, was executed line by line (sequentially) from start to end. But other than the default of executing a script sequentially, you can influence the 'flow' of the execution of your script. You might want to execute a part of your script only in special cases (determined by some condition you set). It is also possible to repeat the execution of one or more lines several times, without putting the command in your script multiple times (copy paste).

This is achieved by the so called control structures. These structures determine the execution of your script. The next section covers the IF-structure and two repetitive structures: the WHILE-loop and the FOR-loop.

Comparisons (tests)

Most control structures use some form of comparison, called tests. Two values are compared and tested. The test will yield true or false. You can compare the value of a variable to a fixed value, but you can also test (the values of) two variables or some form of calculation. Some examples:

$a == 4
equal to; see ! below
$a < 5
less than
$a > $b
greater than
5 >= $b
greater than or equal to
$a <= $b
less than or equal to
$a != (2*$b)
not equal to

! Notice: In comparisons, there is a fundamental difference between == and =

= denotes assigning a value to a variable and will always result in true.

== denotes the comparison of two values. It will only result in true when both values are equal.

IF

if ( $a < $b ) { polyCube -h $a; }

In this example the value of variable $a is compared to the value of variable $b. If (and only if) the value of $a is less than the value of $b (the result of the test is true), the command (or commands) between the curly brackets { ... } is executed.

This structure can be expanded to an If-else structure:

if ( $a < $b ) { polyCube -h $a; } else { polyCube -h 5; move -r 0 4 0; }

The if-part is equal to the example before, but here we've added a part: the keyword else and a second block enclosed by curly brackets. This second block is executed when the test is not true, false.

WHILE loop

float $distance = 0; while ( $distance < 50 ) { polyCube; move -r $distance 0 0; $distance = $distance + 7.2; }

In a While-loop, the command(s) between the curly brackets is executed repeatedly for as long as the test results true.

iteration

The While structure will do the test and only if it results true, the commands between curly brackets are executed. This is called an iteration. After a single iteration, the structure will repeat the events. It will test the expression and if it results true (again), it will execute the commands. If the expression results false it will terminate the entire structure. A loop has zero or more iterations, but in most cases one or more.

infinite loops

If none of the parameters of the expression (comparison) change, the loop will be repeated forever as the test will return true each and every time. If an infnite loop is executed, you need to terminate Maya through the task manager. Not saving any of the files that are open.

Warning: Make sure you don't create an infinite loop and save your script before executing it!

So you need to incorporate a command in a While-loop that influences the test that determines if a next iteration is to be executed.

FOR loop

for ( $i = 1; $i < 10; $i = $i + 1 ) { polyCube; move -r ($i * 3) 0 0; }

Maya script result 001.jpg

The For-loop is a variation to the While-loop. It is often used when 'something' needs to be repeated 'a (counted) number of times'. This type of loop uses a counter that keeps track of the number of iterations.

In the For-loop there are three components between the round brackets separated by semicolons: initialization, condition and iteration.

Initialization
$i = 1
A variable $i that is used as a counter is set to its starting value
Condition
$i < 10
The test that determines whether the loop is continued to be executed. In the example $i must be less than 10.
Iteration
$i = $i + 1
In each iteration this command is executed after the command between curly brackets have been executed. In the example the value of $i is increased by 1.

You can do the exact same thing using a While-loop. It would look something like this:

int $i = 1; while ( $i < 10 ) { polyCube; move -r ($i * 3) 0 0; $i = $i + 1; }

Both options are correct, only the For-loop will be a more clear in most cases. Especially when the commands between curly brackets is very long.

Loop in loop

Loop in Loop

you can create a new loop within the curly brackets of a loop. An example of the application of a loop-in-a-loop is when you want to create a grid of objects:

for ( $i=0; $i < 10; $i++ ) { for ( $j=0; $j < 5; $j++ ) { polyCube; move ($i * 3) 0 ($j * 2); } }


$i++: $i++ is the same as $i = $i + 1. It's a shorthand notation.

Exercise

Personal tools
Actions
Navigation
Tools