March 2019: ewertb.soundlinker.com is getting relocated to ewertb.mayasound.com, please update your bookmarks.

Maya API How-To #27

Back · Previous · Next Maya

How do I access a MEL variable from the API?

There are a few ways to transfer values from MEL to a plug-in:

  1. The correct way (in my opinion) is to construct a MEL command, derived from MPxNode, which accepts the value as an argument and assigns it appropriately within your plug-in.

    float $myValue = 3.14;
    
    myCommand -value $myValue;
    

    When "myCommand" is parsed it will recognize the '-value' flag and assign the specified value to a class variable. This API variable could be static as well, if you wish for the value to be persistent.

  2. Assign the value to an attribute on a dependency node, then read the attribute from the API.

  3. Assign the value to an optionVar, and then read the optionVar from the API.

  4. Write the value to a disk file, and read the disk file from the API.

  5. All of the above are "push" methods; the MEL programmer is responsible for writing the variable to a specific location for the API to obtain its value.

    One "pull" method which doesn't require (much) preparation from the MEL side is to capture the result argument from the MGlobal::executeCommand() method:

    MGlobal::executeCommand( const MString& command, double& result,
                             bool displayEnabled, bool undoEnabled )
    

    One caveat: The variable you need to transfer to the API will need to be in MEL's global declaration space. Globals are evil, so use sparingly.

    // in MEL, declared as a global.
    //
    global float $gToAPI = 3.14;
    
    // in API
    //
    void get_value_from_mel( const MString& var, double& fromMEL )
    {
      // Assembled, the command looks like this:
      //
      //   proc float _floatToAPI() { global float $gToAPI; return $gToAPI; } _floatToAPI();
      //
      MString fromMELCmd( "proc float _floatToAPI() { global float $" );
      fromMELCmd += var;
      fromMELCmd += "; return $";
      fromMELCmd += var;
      fromMELCmd += "; } _floatToAPI();";
    
      MGlobal::executeCommand( fromMELCmd, fromMEL );
    }
    
    double valueFromMEL;
    get_value_from_mel( MString( "gToAPI" ), valueFromMEL );
    

Related How-To's

12 Sep 2004