def

The def command defines a function of your own, which a [expr] can then call.

Syntax

def <name> ( <arg1> { , <arg2> } ) = <expression>

name is the function’s name. arg1, arg2 and so on are its dummy arguments. expression is the body, which runs to the end of the line.

What it does

James stores the function’s text. When a [expr] calls name(x,y), James evaluates the body with each dummy argument bound to the value given. The call must give as many values as the function has arguments.

When James applies it

By the preprocessor, when it is read. The body is evaluated each time the function is called. It is legal in any phase: Control, Part or Merge.

Rules James adds

  • A dummy argument is written without a % in the body, and a parameter is written with one, so the two can never be confused. A dummy argument does not shadow a parameter of the same spelling, and it may share the name of a built-in function such as max or sqrt.
  • Declaring a name again replaces it, whatever kind it held before.

Diagnostics

  • E0208: the call gives a different number of values than the function takes.
  • E0221: the body is not a well-formed expression, reported when the function is called.

Example

The script tests/corpus/160-def-two-arguments/input.tg, which make test runs:

c a def of two arguments, called inside brackets, sets two parameters
def area(w,h) = w*h
para a1 [area(2,3)];
para a2 [area(%a1,2)];
painfo

area takes two arguments, and its body multiplies them. area(2,3) gives 6 and area(%a1,2) gives 12, which painfo prints as a1 = 6 and a2 = 12, after the def area(w,h) = w*h line it prints for the function.

See also

  • para: the parameters a function can read.
  • painfo: prints every function as written.
  • Writing a script: the [expr] form and the functions it knows.

James 0.3.1.

This site uses Just the Docs, a documentation theme for Jekyll.