Creating Functions

From COD Modding & Mapping Wiki
Share/Save/Bookmark
Jump to: navigation, search
Nutshell.png
A custom function is a good way to use repeat sections of code more efficiently. For example, if you often use the same sequence of code, you can template them into a custom function. Imagine this is your code...

Creating Functions

{
 wait 1;
 brush1 moveZ(320, 5);
 brush1 waittill("movedone");
 wait 1;
 brush2 moveZ(540, 3);
 brush2 waittill("movedone");
}

This can be simplified using a custom function, lets call this function "_moveEnt" (it is common practice to use an underscore as the first character of a function)

_moveEnt(ent, dist, time)

As the above shows, we are going to need 3 arguements, ent (entity), dist (distance) and time.

Now lets look at the full code with custom function in use...

 {
   _moveEnt(brush1, 320, 5);
   _moveEnt(brush2, 540, 3);
 }

 _moveEnt(ent, dist, time)
 {
   wait 1;
   ent moveZ(dist, time);
   ent waittill("movedone");
 }

As the above code shows, the custom function can simply be called using the required arguements, which are passed along and used in the new function.

Once the custom function has finished, the script returns to the original location from where it was called.

Functions can also return values to the original script, or even entities.

A simple function to calculate volume from the width, height and depth:

 {
   area = _areaEquation(2, 4, 6);
 }

 _areaEquation(x, y, z)
 {
   answer = x * y * z;
   return answer;
 }

Once the code calls the function '_areaEquation' the function works out the 'answer', 'answer' is the returned. This declares a new variable (area). The variable area, is the answer that is returned by the function.

The two lines:

answer = x * y * z;
return answer;

could be replace by

  return x * y * z;

for the same effect.