The Assignment Statement and Variable

The Assignment Statement

An assignment statement is most important element is the singular equal sign = . After evaluation of an assignment statement, the variable on the left side of the equal sign is set to the value on the right side. Assignment is not limited to being used during declaration. In fact, we are able to set the value of a variable at anytime after declaration and can do so repeatedly. Whenever possible, reuse variables to save on memory usage, seen in Example 4.10.

Example 4.10: Re-declaring a variable value.

    float $tempFloat = 3.48;
    $tempFloat = 3.21212;

Note that when we reassign a new value to the variable $tempFloat, we do not re-declare its type as a float.

The humble assignment statement is the basis for all data gathering within MEL. In Chapter 3, MEL Basics, we learned that most commands contain an aspect called a return value . By putting a MEL command on the right side of the = in an assignment statement, we can capture that return value and assign it to a variable. In order to capture the return value, we enclose the command within single left-hand quotes (`). In Example 4.11, we capture the value of the translate X value of an object called ball, and store that value in a float variable called $translateX.

Example 4.11: Capturing the value returned by the getAttr statement.

    float $translateX = `getAttr ball.translateX` ;

When we use an assignment statement to capture the return value of a command, it is important to assign it to a variable that can actually hold that data. For many beginning scripters, the most frustrating aspect of this comes with array variables when they want to catch only one item. A perfect example is building a selection list when we have only one object selected, seen in Example 4.12.

Example 4.12: Attempting to assign captured data to the wrong type of variable.

    string $object = `ls selected` ;
//ERROR : Cannot cast data of type string[] to string.

The command ls always returns a string array, even if that array is empty or has just one object in it. Data return types for each command can be found within the documentation for that command.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s