Functions

Function gets data, does work and optionally returns value. Each function is composed of signature and statements block. In the signature there is the function key (name) and list of expected parameters. After the signature comes the statements block which can be composed of one or more statements.

In Till there is always a returned value, and the returned value of a function is the returned value of its last executed statement. If the statements block does not contain programmatic entities that change the flow of a program and end the function before its last statement, then the returned value will be the (returned) value of the last statement of the statements block. Otherwise, whenever a flow is terminating the function, the last statement of the flow will yield the returned value of the function.

In case where the function executes only one (one-line) statement, it is possible to append that statement to the function signature in the same line of code (“one-line-function”).

Here are some excerpts from Pi Calculator Project, followed by analysis.

  1. declare function “setstate” with parameter “anyway”
  2. if “anyway” is NULL, set “anyway” to TRUE
  3. in the following statements, run system function “storage.set” with parameters: key, value (variable) and anyway (value of parameter “anyway”)
  4. declare one-line-function “dropstate” that have one statement

In Till function, scalar parameters are passed by value, and parameters of other types are passed by reference.

Functions in this example are: “setstate”, “validatestate”, “getstate” and “showstate”. Function “setstate” is called with parameter “anyway” that gets the value of variable “RESTART”.

System functions in the example are: “not”, “pause”, “print” and “storage.exists”.

Any number of last parameters can be omitted from the calling statement, and the function will refer to these parameters as NULL:

Function “setstate” is called without parameters, thus “anyway” will be NULL.

Passing and using lists in functions

  1. function “func1” has parameter “data” that gets reference to “nums”
  2. function “func2” with parameter “pnums”, returns string scalar “result”
  3. function “func3” gets list variable, copies it to local list “_localnums” that is returned to the caller after changes
  4. function “pkv” gets two parameters “k” and “v”, and returns the result of system function “print”

Well-Defined List Parameter

In Till, variable names that have at least two characters and end with “s”, are well-defined list variables, and if a function parameter meets this criterion, it will be a well-defined list parameter, and will be fit for all list related activities: list position, set, iterator and assignment.

Passing and using records in functions

In the reference there are numerous programs that demonstrate how to use records as function parameters. Here is program “record-func-rec.till”: