Knowledge Base - Modular Programming

Modular Programming

One technique that can be used to simplify scripting is called modular programming. It means to create scripts that can be used more than once. The decision making and looping structure already discussed are designed to facilitate this concept. There are several advantages of using a modular design (now called component based design), but the biggest is the idea of encapsulation. In ZDoom this means making a single script do multiple things, without the script itself having to know all the details.

This may sound confusing, but in practice it is quite simple. Take an example, where three switches have to be activated in order for a door to open. The script itself, doesn't have to have each switch id coded into the script. It just knows what to do when all the switches have been thrown.

int switchcnt;

script 1 (int doorid)
{
	switchcnt++;
	if (switchcnt == 3)
		Door_Open (doorid, 16);
}

This script doesn't know or care about the switch. Rather, it knows to increment the counter and if the proper condition is reached, to open the door marked with doorid.

A script can even be more general.

script 1 (int mapspotid, int thingtype, int angle)
{
	Thing_Spawn (mapspotid, thingtype, angle);
}

This script can be used to spawn any item at the passed mapspot, and with the passed angle. This script is only concerned about one thing, spawning an item. The above script may seem trivial, but combined with proper id placement, it can be quite powerful. For example, this script could be called with an id that corresponds to several monsters that need to be spawned as a group.

By consolidating and generalizing scripts, the scripting becomes much simpler. A simple script is easier to understand and is less likely to have errors. Simple is better.

Back