> ## Documentation Index
> Fetch the complete documentation index at: https://gocharting.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Your own functions

> Declaring functions with func and def, parameters and defaults, return values and tuples, and what a function may and may not change.

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

## Declaring

```lipi theme={"languages":{"custom":["/languages/lipi.json","/languages/lipi-invalid.json"]}}
//@lipi=2
indicator("Scaled range")
func scaled(float x, float k = 2.0) => x * k
func midpoint(float a, float b) {
    float m = (a + b) / 2
    return m
}
plot(midpoint(high, low) + scaled(1, k=0.5), title="Middle")
```

* `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](https://gocharting.com/docs/scripting/language/qualifiers.md)); 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.

```lipi-fragment theme={"languages":{"custom":["/languages/lipi.json","/languages/lipi-invalid.json"]}}
func spread(float a, float b) => [math.min(a, b), math.max(a, b)]
[lo, hi] = spread(open, close)
```

`[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:

| Inside a function | Result |
| - | - |
| `:=`, `+=` and the like on a global variable | refused: Cannot modify global variable `hits` in function. |
| `hits = 1` where `hits` is global | declares a new local `hits`, with a warning |
| `array.push(arr, x)` or `arr.set(...)` on a global or passed array | works |
| `p.price := v` on a global or passed object | works |
| `plot`, `hline`, `fill`, `bgcolor` and the rest of the plot family | refused (see [Branching](https://gocharting.com/docs/scripting/language/branching.md)) |

```lipi-invalid theme={"languages":{"custom":["/languages/lipi.json","/languages/lipi-invalid.json"]}}
//@lipi=2
indicator("Counter")
static int hits = 0
func bump() {
    hits += 1
    return hits
}
plot(bump())
```

The compiler says: Cannot modify global variable `hits` in function. Return the value and assign it outside:

```lipi theme={"languages":{"custom":["/languages/lipi.json","/languages/lipi-invalid.json"]}}
//@lipi=2
indicator("Rising bars")
static int hits = 0
func bumped(int n, bool up) => up ? n + 1 : n
hits := bumped(hits, close > open)
plot(hits)
```

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](https://gocharting.com/docs/scripting/evaluation/call-contract.md)).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.