Skip to main content
A function names a calculation you use more than once. Declare it at the top level, above the first line that calls it.

Declaring

  • func name(params) => expression returns the expression. func name(params) { with a body and return value is the long form. With no keyword, name(params) => expr declares the same kind of function; use func. def declares something else (below).
  • Each parameter has a type: func f(x) => x is a syntax error. A const, simple or series word may come first (see qualifiers); with none it is series. const and simple only go with int, float, bool, string and color: for an array, object or drawing write series or nothing (Cannot use the const keyword when declaring a variable or parameter that accepts a non fundamental type.). A default is a literal or a built-in such as close, not a calculation.
  • Functions of one name may differ in their parameters (f(float x) and f(string s)); two with the same parameter types are refused: The f function has overloads with the same parameters.
  • Call with positional arguments, then named ones. A long-form function that returns a value must return on every path, and all returns must agree on type: The f() function is missing return statement. A switch does not help: with a return in every case and the default it is still missing, and a switch in a called function passes the editor’s check but is refused on Add to chart (Not Implemented). Use if and else. A body with no return returns nothing: call it as a statement; assigning it is refused (Cannot assign void value.).
  • A function may call functions declared above it, not itself and not one below it, so there is no recursion: a call to itself gives Function fact is not available here. Functions must be defined before use, and cannot call themselves. Use a loop instead.

Returning several values

Return a tuple in brackets and unpack it with a bracketed declaration; the counts must match and the types may differ.
[lo, hi] := spread(...) assigns existing variables. A tuple cannot go into a single variable, and the names take no types: [float lo, float hi] = ... gives no viable alternative at input ‘[float’.

What a function may change

A function reads global variables freely. What it may change is limited:
The compiler says: Cannot modify global variable hits in function. Return the value and assign it outside:
An object or array is shared, not copied, so the caller sees a change to its contents. def name(Type x, ...) declares a type function, not an ordinary one: x is the receiver, so it is also called as value.name(...). It needs at least one parameter (def one() => 1 gives Type Function should have at least one parameter.), and a func cannot be called with the dot. History used inside a function (x[1], talib.*) belongs to its call site, so call the function on every bar (see Calls that must run on every bar).