ZScript functions

From ZDoom Wiki
Jump to navigation Jump to 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. If you do encounter slowdown, worry about getting the correct results first before optimizing. In very old versions of GZDoom, function calls could seriously harm performance, but with the addition of the JIT and the overhaul of the ZScript calling convention, this is not the case anymore. If you're having issues with performance, the problem will almost always lie in the code, rather than being due to function call overhead.

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);

Referencing

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;
}

Limits

While in practice this should never be an issue, functions in ZScript do have a maximum number of resources available for use, and this 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