Mel Script - Declaring mel procedures

 

 

 

Procedures allow us to collect together a series of commands into a new function that will perform our actions. This allows us to make much more generalised statements such as, deleteAllMeshes(), processAllVertices() etc.

By using much higher level processes within our scripts we are able to make much easier to undrestand code.

 

 

 

 

 

Example 1 : deleteAllMeshes()

To declare a procedure, use the proc keyword.

 

 

 

	
	{
		// declare a procedure to delete all meshes in the scene 
		proc deleteAllMeshes()
		{
			// get a list of all meshes
			$meshes = `ls -type "mesh"`;
			
			// loop through each mesh and delete
			for($mesh in $meshes) {
				delete $mesh;
			}
		}
		
		// call the procedure
		deleteAllMeshes();
	}
	

 

 

Example 2 : arguments

Providing arguments to the procedures allows us to vary the process undertaken by a function, thus making it more flexible and better for later re-use. Declaring arguments is much the same as in C, you specify a type and a variable name in a comma seperated list.

 

 

	
	{
		// declare a procedure to create some objects
		proc createObjects(int $num_cubes,int $num_spheres)
		{
			// generate the number of required cubes
			for($i=0;$i<$num_cubes;++$i) {

				// create a cube
				polyCube;

				// transform into the correct location
				xform -t $i 0 -2;
			}
			// generate the number of required spheres
			for($i=0;$i<$num_spheres;++$i) {

				// create a sphere
				polySphere;

				// transform into the correct location
				xform -t $i 0 2;
			}
		}
		
		// call the procedure
		createObjects(10,5);
	}
	

 

 

Example 3 : Return Arguments

A return argument is used when the function or procedure you are writing requires a calculation to be performed and a result needs to be returned. mel handles return arguments from a function in much the same way as C or C++. You must first declare the data type you will be returning, and then use the return statement to return the required value.

 

 

	
	{
		// declare a procedure to add 2 numbers together
		proc float addTwoNumbers(float $a,float $b)
		{
			// return the result of (a+b)
			return $a + $b;
		}
		
		// call the procedure and print
		print( addTwoNumbers(10.03,5.98) + "\n");
	}