FOR and WHILE loops

From ZDoom Wiki
Jump to: navigation, search

LOOPS can reduce the size of a script dramatically, when an action must be performed repeatedly.

In this script are several sectors, here 1 to X. Of course, X must be replaced with the highest sector ID number. Each sector has the Floor_Waggle special.

This is easily a copy and paste setup, but the sector IDs must then be changed manually. The script could be written like this:

#include "zcommon.acs"
SCRIPT 1 OPEN
{
	Floor_Waggle  ( 1, 200, 50, 0, 0 );
	delay (5);
	Floor_Waggle  ( 2, 200, 50, 0, 0 );
	delay (5);
	Floor_Waggle  ( 3, 200, 50, 0, 0 );
	delay (5);

                      |
                      |
                      |

	Floor_Waggle  ( X, 200, 50, 0, 0 );
	delay (5);
}


An easier way would be, if a script were to update the sector IDs in a loop. Either a FOR loop or a WHILE loop could be used.

FOR loop

The for loop can be written in two ways, the difference is how the variable is declared.

#include "zcommon.acs"
SCRIPT 1 OPEN
{
	for ( int sid = 1; sid < X; sid++ )  // sid is the sector ID
    {
	Floor_Waggle ( sid, 200, 50, 0, 0);
	delay (7); 
    }
}

or this

#include "zcommon.acs"
script 1 open
{
	int sid = 0;
	
	for ( sid = 1; sid < X; sid++ )  // sid is the sector ID
	  {
	    Floor_Waggle ( sid , 100 , 20 , 0 , 0 );
  	    delay (7);
	  }
}


WHILE loop

#include "zcommon.acs"
script 1 open
{
	int sid = 1;  // sid is the sector ID
	
	while ( sid < X )
   {
		Floor_Waggle ( sid, 100, 20, 0, 0) ;
		delay (7);  
		sid++ ;
    }
}

In a case like this, the desision to use either the for or the while loop comes down to a programmer's preference, because in the for loop all loop control statements are in one place.

Personal tools
Namespaces
Variants
Actions
Navigation
ACS
DECORATE
ZDoom mods
Toolbox