一半君的总结纸

听话只听一半君

#109 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

Advertisements

发表评论

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

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

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

Facebook photo

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

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: