Declaring
func name(params) => expressionreturns the expression.func name(params) {with a body andreturn valueis the long form. With no keyword,name(params) => exprdeclares the same kind of function; usefunc.defdeclares something else (below).- Each parameter has a type:
func f(x) => xis a syntax error. Aconst,simpleorseriesword may come first (see qualifiers); with none it isseries.constandsimpleonly go withint,float,bool,stringandcolor: for an array, object or drawing writeseriesor nothing (Cannot use theconstkeyword when declaring a variable or parameter that accepts a non fundamental type.). A default is a literal or a built-in such asclose, not a calculation. - Functions of one name may differ in their parameters (
f(float x)andf(string s)); two with the same parameter types are refused: Theffunction 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. Aswitchdoes not help: with areturnin every case and thedefaultit is still missing, and aswitchin a called function passes the editor’s check but is refused on Add to chart (Not Implemented). Useifandelse. A body with noreturnreturns 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
factis 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:hits in function. Return the value and assign it outside:
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).