MEL How-To #99

Back · Previous · Next Maya

How do I query the field names from an enumerated attribute?

The '-enumName' flag for the "addAttr" command is queryable, and may be used to acquire a string for the labels of an enumerated attribute.

Consider an enumeration created as follows:

addAttr -at "enum" -ln "myEnum" -enumName "solo=1:triplet=2:quintet=3" shape;

To query the fields:

string $enumFields = `addAttr -q -enumName shape.myEnum`;
// Result: solo=1:triplet:quintet //

You can tokenize this string to extract an individual value.

string $tokens[];

tokenize $enumFields ":" $tokens;
// Result: { "solo=1", "triplet", "quintet" } //

By default the first field of an enum will be associated with a value of 0 (zero) and subsequent fields will increment this value by one. However, Maya allows to you specify arbitrary field values, and you'll need to do a bit more processing to determine what values are associated with each field.

addAttr -at "enum" -ln "myOtherEnum" -enumName "first=2:second:third=5:other=0" shape;

addAttr -q -enumName shape.myOtherEnum;
// Result: other:first=2:second:third=5 //

The example above uses the following field/value associations:


The following MEL will generate the field values for the enumeration.

// Query the enumeration fields from the enumerated attribute.
string $enumFields = `addAttr -q -enumName shape.myOtherEnum`;

// Prepare string arrays for our tokenizing
string $enumTokens[];
string $fieldTokens[];

// Extract the fields from the enumeration string.
tokenize $enumFields ":" $enumTokens;

// Print the field value for each.
int $fieldValue = 0;
for ( $token in $enumTokens )
  // If this field specifies its own value, use it.
  int $numTokens = `tokenize $token "=" $fieldTokens`;
  if ( $numTokens > 1 )
    $fieldValue = $fieldTokens[1];

  // Print it.  
  print ( "\"" + $fieldTokens[0] + "\" = " + $fieldValue + "\n" );

  // Increment field value as default for next enumeration.

The result:

"other" = 0
"first" = 2
"second" = 3
"third" = 5

And for '.myEnum':

"solo" = 1
"triplet" = 2
"quintet" = 3


This technique may be used only for dynamic attributes. The "addAttr" command does not allow for querying the enumeration fields from a native Maya attribute:

getAttr -type locatorShape1.nodeState;
// Result: enum //

addAttr -q -enumName locatorShape1.nodeState;
// Error: 'nodeState' is not a dynamic attribute of node 'locatorShape1'. //


Erick Miller, Digital Domain

28 Apr 2004