MEL How-To #61

Back · Previous · Next Maya

How can I create a MEL procedure that can accept multiple (and optional) flags or arguments?

Unfortunately, MEL does not support overloaded procedure declarations, variable argument lists or default argument assignments. Thus it requires extra work to create a MEL command that can accept a varying argument list, such as:

processPolys -planar;

processPolys -textured -triangles;

There are two ways you could implement support for multiple arguments. In neither case will you be able to use the syntax form suggested above, however. MEL will expect the arguments in a more formal format.

Method #1: Single String Argument

The first way is to accept a single string argument which encapsulates all arguments. This will be tokenized within the MEL script and options will be extracted and parsed.

global proc processPolys( string $argList )
{
  // Set defaults first
  int $optionPlanar = false;
  int $optionTriangles = false;

  string $argData[];

  // Separate space-delimited arguments into argument array
  tokenize $argList " " $argData;

  for ( $arg in $argData )
  {
    switch( $arg )
    {
      case "-planar":
        $optionPlanar = true;
        break;
      case "-triangles":
        $optionTriangles = true;
        break;
      // A NULL string will parse to a single token?
      case ""
        break;
      default:
        error ( "Unsupported flag: " + $arg );
    }
  }

  // Continue with script execution.
}

Examples

processPolys "-planar -triangles";

// Single argument
processPolys "-planar";

// Nope, not this way...
processPolys;
// Error: Line 1.13: Wrong number of arguments on call to processPolys. //

// To use defaults, specify empty string to declare no options
processPolys "";

Method #2: String Array Argument

Another form of "variable argument list" is to declare a single argument as a string array and allow the user to be able to include as many options within the array as needed. Parsing would be identical to the method above, but the string array would eliminate the need to tokenize them from a single string. That's really the only difference.

global proc processPolys( string $argData[] )
{
  // Set defaults first
  int $optionPlanar = false;
  int $optionTriangles = false;

  // No need to tokenize into an array as we already have one.

  // Now process any arguments specified by the user

  // ... same as above.
}

Examples

processPolys { "-planar", "-triangles" };

// Single argument
processPolys { "-planar" };

// Nope, not this way...
processPolys;
// Error: Line 1.9: Wrong number of arguments on call to processPolys. //

// To use defaults, specify empty array to declare no options
processPolys { };

Tuesday, March 27, 2001