MEL How-To #109

Back · Previous Maya

How do I retrieve or replace a single element from an array optionVar?

The optionVar command allows you to save multiple values in a single preference location. However, its ability to access individual elements of this array is rather limited.

To access the n'th item in an optionVar you'll need to query the entire array, and extract the item in which you're interested:

// Index of the element to query.
//
int $index = 3;

// Value at the specified index.
//
string $value = "";

if ( $index >= 0 )
{
  if ( `optionVar -exists stringArrayOptionVar` )
  {
    // Query the entire array.
    //
    string $vars[] = `optionVar -q stringArrayOptionVar`;

    // If the element exists, assign it to our result.
    //
    if ( $index < `size $vars` )
    {
      $value = $vars[$index];
    }
  }  
}  

Replacing or inserting an n'th item requires rebuilding the entire array for the optionVar:

// Index of the element to assign.
//
int $index = 7;

if ( $index >= 0 )
{
  // Array contents of the optionVar
  //
  string $vars[];

  if ( `optionVar -exists stringArrayOptionVar` )
  {
    $vars = `optionVar -q stringArrayOptionVar`;
  }  

  // This index restriction allows only replacing of existing elements;
  // remove this to allow for insertion of new elements.
  //
  if ( $index < `size $vars` )
  {
    $vars[$index] = "value";
  }  

  // Must first clear the entire array.
  //
  optionVar -clearArray stringArrayOptionVar;

  // …then insert the elements and rebuild the optionVar.
  //
  for ( $item in $vars )
  {
    optionVar -sva stringArrayOptionVar $item;
  }
}  

Related How-To's

02 Apr 2006