Skip to content

User defined functions

Jordan Leppert edited this page Apr 28, 2024 · 12 revisions

A user-defined function is a file containing statements. This can be executed with parameters, enabling users to create their own functions.

Input

When a user-defined function is executed, the parameters are injected into the calculator state as the variables PARAM1, PARAM2 etc. The first parameter is called PARAM1.

For easier testing of a function, the ||= operator can be used to set a PARAM variable to a value if it does not already have a value. For example, if a user-defined function has three parameters, putting this at the top of the file lets you test the function while writing it by defaulting these parameters to some test values.

PARAM1 ||= 1
PARAM2 ||= 2
PARAM3 ||= 3

PARAM1 / PARAM2 + PARAM3

Input validation

You may want to restrict the parameters to your function to particular types (e.g. number, boolean etc), or particular unit dimensions (e.g. time, mass etc). You will need to do this if your function takes an array as a parameter, otherwise your user-defined function will be executed once for each element in the array, passing in a single element at a time.

To restrict the parameters for a user-defined function to particular types and unit dimensions, put this as the top line to the function, repeating for as many parameters as you have, separating each parameter definition by spaces:

#INPUT <PARAM1 restriction> <PARAM2 restriction> ... <PARAM<n> restriction>

Each parameter restriction is a type, optionally followed by a colon and a unit dimensions specification.

<type>[:<unit dimensions]>

See type reference for the list of types you can use.

The unit dimensions specification is a comma-separated list of unit dimensions, each optionally with a power (which defaults to one).

<dimension>[^<power>][,<dimension>[^<power>]]

See units reference for a list of unit dimensions you can use.

Example, this function takes six parameters:

  1. number
  2. string
  3. boolean
  4. array of numbers
  5. number, with a mass unit
  6. number, with an acceleration unit (distance over time squared)
#INPUT number string boolean array[number] number:mass number:distance,time^2

Output

The final statement of the user-defined function is the function's output.

Execution

To execute a user-defined function:

  1. Create a variable with the path to the user-defined function file as a string value.
  2. Execute the function by entering @ followed by the variable name, followed by brackets containing the parameters to the function.

Example:

ext_func = '/path/to/file'

# Executes the function in file '/path/to/file' with parameters: 1, 2, 3
@ext_func(1, 2, 3)

Clone this wiki locally