Chapter 10. User-Defined Functions
User-defined functions are one of the most important characteristics of any modern programming language. They provide the programmer with the ability to write modular programs and create reusable code components. Over the course of time a good programmer will build up a powerful toolbox of regularly-used functions that have been well-tested. This toolbox of functions enables the programmer to produce powerful and reliable programs quickly and easily.
Defining and Calling Functions
To define a function the keyword function
is placed at
the beginning of the line and outside the body of any other function.
That is followed by at least one space and then the name of the function.
Following the name is an opening parenthesis, the parameter list and then
the closing parenthesis. The parameter list may be empty. If it is not, then
the parameters are listed starting with their type and then the name of the
parameter. A default value can also be assigned to a parameter by placing
an equals sign after the parameter. The entire syntax diagram would look
like: function <name>([<parameter type> <parameter
name>[=<value>],…])
. The return value of the
function is placed on the last line of the function following the
end function
statement. This can be a variable, an
expression, or even the entire function body (assuming it is a single
statement). A function does not need to return a value.
To call a function it is sufficient to place the name of the function followed by the open parenthesis, the argument list, and the close parenthesis in the program code. If the function returns a value that can be assigned to a variable or used within an equation. Even if a function returns a value that value can be ignored if the programmer so chooses. The following is an example of the definition and calling of a function:
function main() end function hello("world") function hello(string s) string t t = "hello " + s end function t