Subroutines are similar to mathematical functions (see Section 4.3), and once defined, can be used anywhere in algebraic expressions, just as functions can be. However, instead of being defined by a single algebraic expression, whenever a subroutine is evaluated, a block of PyXPlot commands of arbitrary length is executed. This gives much greater flexibility for implementing complex algorithms. Subroutines are defined using the following syntax:
subroutine <name>(<variable1>,...) { ... return <value> }
Where name is the name of the subroutine, variable1 is an argument taken by the subroutine, and the value passed to the return statement is the value returned to the caller. Once the return statement is reached, execution of the subroutine is terminated. The following two examples would produce entirely equivalent results:
f(x,y) = x*sin(y) subroutine f(x,y) { return x*sin(y) }
In either case, the function/subroutine could be evaluated by typing:
print f(1,pi/2)
If a subroutine ends without any value being returned using the return statement, then a value of zero is returned.
Subroutines may serve one of two purposes. In many cases they are used to implement complicated mathematical functions for which no simple algebraic expression may be given. Secondly, they may be used to repetitively execute a set of commands whenever they are required. In the latter case, the subroutine may not have a return value, but may merely be used as a mechanism for encapsulating a block of commands. In this case, the call command may be used to execute a subroutine, discarding any return value which it may produce, as in the example:
pyxplot> subroutine f(x,y)
subrtne> {
subrtne> print "%s - %s = %s"%(x,y,x-y)
subrtne> }
pyxplot> call f(2,1)
2 - 1 = 1
pyxplot> call f(5*unit(inch), 10*unit(mm))
127 mm - 10 mm = 117 mm
The dynamics of the simple pendulum.