# Touhou Danmakufu: Functions and Subroutines

*7,301*pages on

this wiki

- Return to Touhou Danmakufu: Syntax

## Subroutines

Often-used codes can be shared as subroutine.

sub (name) { (statements) }

In the following case,

sub fire { CreateShot01(GetX, GetY, 5, GetAngleToPlayer, RED01, 0); }

fire; fire;

is equivalent to:

CreateShot01(GetX, GetY, 5, GetAngleToPlayer, RED01, 0); CreateShot01(GetX, GetY, 5, GetAngleToPlayer, RED01, 0);

Subroutines can be used not only to share codes but also to give names to processes. Both code-sharing and naming improve the maintainability of the program.

## Functions

If the often-used codes require some parameters, or the calculational results need to be returned, functions are used instead of subroutines.

function (name) ( (parameter list) ) { (statements) }

e.g. a mathematical function

f(x) = x^{2}+ 2

is represented in Danmakufu as follows:

function f(x) { return x ^ 2 + 2; }

where **f** is the function name, **x** is the parameter, and **x ^ 2 + 2** is the function's value. **return** statement defines the function's value with parameter **x**. In this case, the value of **f(2)** is 2^{2} + 2 = 6.

Functions can be used as subroutines. In fact, functions having no parameters and no return values are equivalent to subroutines as:

function fire { CreateShot01(GetX, GetY, 5, GetAngleToPlayer, RED01, 0); }

However, functions are little bit slower than subroutines.

Functions are often used as parametrized subroutines. e.g.

function fire(v) { CreateShot01(GetX, GetY, v, GetAngleToPlayer, RED01, 0); }

In this case,

fire(3); fire(5);

is equivalent to:

CreateShot01(GetX, GetY, 3, GetAngleToPlayer, RED01, 0); CreateShot01(GetX, GetY, 5, GetAngleToPlayer, RED01, 0);

The **CreateShot01**, **GetX**, **GetY**, and **GetAngleToPlayer** are functions, too. There are many pre-defined functions as them. For details, see Touhou Danmakufu: Functions.

- Return to Touhou Danmakufu: Syntax