Mel Script - the while loop




A while loop is used within programming whenever we need to repeat something an unknown number of times. The loop will continue to repeat whilst the sentinal condition is true. You must therefore be very careful to ensure that your loop will actually terminate!! You should use a while loop whenever you do not know how many times you need to loop, ie; while not at the end of the file; while the program is running; while the user is inputting value.....

The general form for a while loop is as follows :




		while( <sentinal condition> ) {
			// action to repeat



Example 1 : A basic while loop example

A common place you will see a while loop is when you are reading a file. Since we do not know the size of the file, we need to loop until we reach the end.



		// construct the full path to a file
		$filename = (`internalVar -userPrefDir` + "windowPrefs.mel");
		// open the file for reading
		$file = `fopen $filename "r"`;

		// loop UNTIL we reach the end of the file
		while( !feof($file) )
			// read a word from the file and print
			print( `fgetword $file` + "\n" );
		// close the file
		fclose $file;