Mel Script - the if-else statement

 

 

 

Whenever you are programming, one fundamental aspect is the ability to ask a question. The main construct available to do this is the if statement and the if/else statement.

The if statement simply takes a conditional expression (ie, it evaluates to true or false) and will perform a set of actions if that condition is true. The general form of an if statement is as follows :

 

 

 


		if( <condition> ) {
			// action to perform if <condition> is true
		}

 

 

Example 1 : A simple if statement

This simple example uses ls to retrieve a list of all the meshes in the scene. If no meshes are present then the size of the array returned must be zero. Therefore, the if statement is just checking for this possibility.

 

 

	{
		// get a list of all meshes in the scene
		string $nodes[] = `ls -type "mesh"`;

		// if there are no meshes, inform the user. 
		if( size($nodes) == 0 ) 
		{
			// print the name of the mesh
			print( "There are no meshes in the scene!\n" );
		}
	}

 

 

The if-else statement

The if else statement allows you to provide two possible sets of actions to perform depending on the outcome of the conditional expression. The general form is :

 

 


		if( <condition> ) {
			// action to perform if <condition> is true
		} 
		else {
			// action to perform if <condition> is false
		}

 

 

Example 2 : A simple if-else statement

This extends the previous example by adding in an else statement to handle both possibilities that there may or may not be any mesh nodes.

 

 

	
	{
		// get a list of all meshes in the scene
		string $nodes[] = `ls -type "mesh"`;

		// if there are no meshes, inform the user. 
		if( size($nodes) == 0 ) 
		{
			// print the name of the mesh
			print( "There are no meshes in the scene!\n" );
		} 
		else {
			print( "Found " + size($nodes) + " meshes in the scene\n" );
		}
	}