Mel Script - Using eval()

 

 

 

Often when using mel, the code to be executed is not known until runtime. In this situation, you should make use of eval to execute the code.

 

 

 

 

Example 1 : a very simple example

fgetword simply reads the next word in the file and returns it as a text string.

 

 

	
	{
		// a set of possible command that could be executed
		string $commands[] = { "polyCone", "polyCube", "polySphere", "polyTorus" };

		// repeast a few times
		for( $i=-10; $i<=10; $i+=2 )
		{
			for( $j=-10; $j<=10; $j+=2 )
			{
				// generate a random number to use as an index into the commands array
				int $index = `rand 4`;
				
				// call eval to execute the command
				eval($commands[$index]);
				
				// move the object
				xform -t $i 0 $j;
			}
		}
	}

 

 

Example 2 : passing arguments to eval

fgetline simply reads a line of text from the file and returns it as a string.

 

 

		
		// a simple function we have declared. Within eval, we are going to attempt
		// to call this and pass it an argument.
		//
		global proc myFunc(string $text) {
			print($text);
		}

		{
			// a text string we want to pass to myFunc within eval.
			string $some_text="hello world";
			
			// this WILL NOT WORK!! When eval executes, $some_text will no longer
			// be in scope. Maya will therefore fail to recognise $some_text as a valid 
			// variable. To handle this situation, you will need to expand the value of 
			// the variable into the text string. 
			eval( "myFunc($some_text);" );
			
			// this is the way to do it.... The string we pass to eval will now
			// read:  myFunc("hello world") and thus works....
			eval( "myFunc( " + $some_text + ");" );
		}