ZScript functions

From ZDoom Wiki
Jump to: navigation, search
Note: This feature is for ZScript only.

Functions are created similarly to how they are made in many different programming languages.

int MyFunction(int MyNumber, int Another)
	return MyNumber + Another;

PERFORMANCE NOTE: Functions are useful, and should be used for clean code, especially code that is redundant as this will overall help performance and readability; however, each time a function is called within another function there is additional overhead for the virtual machine, which could add up rapidly if you're doing multiple complex actions every tic for many actors at once. If you do encounter slowdown, worry about getting the correct results first before optimizing - and ensure whatever sub-functions you're replacing get proper comments.

Using the console command

stat vm

is helpful for seeing performance/benchmarking of ZScript in general.

Multiple Returns

Functions are capable of returning multiple variables at once. All it needs is the return types defined with a comma between each, and for the return statement to also contain the ideal variables like such:

// Returns two ints and a bool.
int, int, bool MyFunction(int MyNumber, Another)
	return MyNumber, Another, true;

The call to the function does not require all assignments to be filled, only up to the necessary one on the right. Note that an actual non-constant variable of the appropriate type is required for each.

// If only the second return is desired (where 'b' is), the previous (left) variables need a temporary assignment. Anything after does not.
int a, b;
[a, b] = MyFunction(1, 2);


As described with ZScript special words, 'in' and/or 'out' can be used to specify sending in a variable for direct modification. This is especially useful if passing structs around, which can alleviate the problem of having so many parameters, and modifying variables of things that otherwise cannot be returned (such as structs themselves). A simple struct must be defined though:

Struct MyStruct
	int a, b;

With the struct defined, simply pass it in like this:

void ChangeStructNumbers (in out MyStruct strct)
	strct.a = 1;
	strct.b = 2;


Functions in ZScript have a maximum number of resources available for use, and must be kept in mind when designing them:

  • 32767 integer constants
  • 32767 string constants
  • 32767 float constants
  • 32767 address constants (this includes all function addresses, RNGs or other native resources being referenced.)
  • 256 integer registers
  • 256 floating point registers
  • 256 string registers
  • 256 address registers