# Functions in depth: editions, parameters, inline, lambdas, several values
`edition 2` vs edition 1, parameter types and kinds, `ref`, defaults, `return a, b` and destructuring, `inline function`, lambdas `x -> ...`, `@icon` / `@description`, row and module length limits. Open when writing helpers, recursion, struct methods or old (edition 1) files.

## Editions
Always start a new file with `edition 2`. A file without it is "edition 1" (old files, docs/recipes*.jc): same syntax, but
`var` and parameters are shared with called functions (below); `jmvcc migrate file.jc` converts one.
- Edition 1 (no `edition 2` line): `var` is the thread variable (= `local var`) — called functions SEE AND CHANGE it;
  `line var` is the own one.
- `var x` (no value) declares without emitting code (a new `var` is 0). Edition 1: inside a function it is the caller's `x`;
  edition 2: the function's own empty one — share with `local var x` in both places.

## Taking values apart
- Taking values apart: `var [a, b] = [1, x + 1]` (= `var a = 1; var b = x + 1`), `var [q, r] = divmod(17, 5)` (a function
  with `return a, b`, see «Several return values» below), `var [x, _, z] = l` (a list: `x = l[0]; z = l[2]`, ≈1 each; a missing element is 0;
  `_` skips a value), `var [x, y, z] = loc` (a location: x y z yaw pitch by get_coordinate, = `loc.x`; a vector: x y z by
  get_vector_component; never get_list_value — on a location that is a server error that stops the line), `game var [w, h] = [16, 9]`.
  The kind must be visible: a variable / parameter of unseen kind (`function g(l)`) is an error `destructure-kind` — give it
  `l: list` or read `l[0]` / `loc.x` yourself; a function result of unseen kind is taken as a list. Existing names: `a, b = 1, 2`, `a, b = f()`, `a, b = l`, swap
  `a, b = b, a` (all values are read first; a temp only for a cycle: swap = 3 actions), `l[i], l[j] = l[j], l[i]`;
  `[a, b] = [b, a]` is the same. The number of names must equal the number of values (`destructure-count`; a list — any).
  `var a, b = f()` keeps its old meaning (a without a value, b = the whole f()): with a function of several values it is
  an error `destructure-var-pair` — write `var [a, b] = f()`. No nested `[a, [b, c]]`, no `...rest`, no `{a, b} = m`.

## inline function and lambdas
Small helpers — `inline function`: no function on the server, the body is compiled at every call (exactly the
code you would write there by hand):
```js
inline function sq(x) { return x * x }          // b = sq(i) → b = i * i: ≈3 instead of ≈10 for a call with return
inline function low(h) { return h < 5 }         // if (low(hp)) → if (hp < 5): ≈1 instead of ≈13
inline function clampz(x) { if (x < 0) { return 0 } return x }   // guard return → if / else
inline function add(x, n = 1) { x += n }        // add(coins) writes coins itself; add(n = 3, x = hp) works too
inline function heal(self: Run, n) { self.hp += n }   // struct parameter: %player%.heal(5) = %player%.hp += 5
inline function each_alive(body: fn) { for (name in alive) { body(name) } }   // body: fn — code
each_alive { n -> log("$n") }                    // a block after the call = the last fn parameter
var big = count_if(scores, x -> x > limit)      // a lambda sees your variables (limit)
apply(hp, bump)                                  // a function name: body(v) is bump(v)
```
- Lambdas exist ONLY as arguments of an inline function's `name: fn` parameter (compile time; the server has no
  code values): `x -> expr`, `(a, b) -> expr`, `() -> expr`, a block `{ x -> ... }` / `{ ... }` after the call
  (`f(l) { x -> }`, `l.each { x -> }`, `f { }`), the name of a function, or another fn parameter passed on.
  `body(v)` in the body pastes the lambda (its value) or the block (statements; no value) with `v` bound like an
  argument. In a block `continue` / `break` act on the loop it landed in, `return` leaves YOUR function.
  `var f = body`, a lambda in an action or a normal function — `lambda-as-value`; wrong count — `fn-arity`.
- Arguments: a constant is substituted, a variable IS that variable (a write in the body writes it — in `edition 2`
  files parameters are by value and `ref x` is the caller's variable, exactly as for `function`), anything else (`i + 1`, `l[0]`, `value::health`) is computed
  once into a `line var` at the call, left to right. Defaults and named arguments as for `function`.
- `var t = ...`, loop variables and `{ i, v -> }` in the body get fresh names (`jmcc.N`): the caller's `t` is
  untouched; `var x` without a value is the caller's `x` (edition 2: its own, empty; `local var x` — the caller's). The body sees its parameters, its own names, globals and
  top-level `const` / `inline var` — not the caller's locals.
- `return`: at the end, in the last statement's if / else / match branches, or `if (c) { ...; return a }` followed by
  the rest (becomes if / else). `return` inside a loop of the body, or `break` / `continue` outside the body's own
  loops — error (`inline-return-position`, `inline-break`): return a flag instead.
- Not for recursion (`inline-recursion`, the chain is shown), `code::call_function("f")`, `rpc`, `process`
  (`inline-no-server-function`). A name is either inline or a normal function. Declared at the top level; visible
  above the declaration and through `import`. An error in the body points at the body line + "вызвано из main.jc:40".
- Every call repeats the body: a code row over 67 blocks after expansions → warning `row-too-long` with the biggest
  ones — remove `inline` from those (past 67 the row is cut into a helper function anyway, which costs a call).

## Functions
function sq(x) { return x * x }
var a = sq(3) + sq(4)               // return value; works for functions declared below too
function check(n) { if (n < 0) { return 0 } return n }   // return on EVERY path, or the old value leaks
function is_top(n) { return n > 5 }                    // a condition returns 1/0; return true/false too
if (is_top(score) && !is_top(other)) { ... }           // only yes/no functions work directly as a condition
repeat::while(is_top(i) == 1) { ... }                  // in while compare explicitly (re-called every step)
```
## Parameter types and kinds
Parameter types (optional): `function f(n: number, t: text, l: list, m: map, v: vector, p: location, i: item, s: Phase)`.
A type picks the JMVCC name (`m.length()` → map size, `m[k]` → map) and a call with a clearly different kind is
an error (`param-kind-mismatch`: `f([1, 2])` for `m: map`). In edition 2 the type also goes to the server, which CHECKS it
at every call: `n: number` called with "abc" stops the line ("5" passes as 5); no type — any value. Edition 1: no runtime check. `string`/`int`/`array`/`dict`
work with a warning; `bool` = yes/no: a number 1/0 (`true`/`false` in the call become 1/0), `if (on)` works. Without a type the compiler looks at EVERY call
of `f` (the file and its imports, also through `g(y) { f(y) }` — a typed `f(m: map)` is checked that way too;
`if (x.contains(v))` and `x.slice(0, 2).length()` on such a parameter work the same): one kind everywhere → that action, silently;
different kinds → a runtime check `variable::is_type` (one check for 2 kinds, two for 3; adjacent calls on the
same parameter share it) plus a `kind-mixed` warning — if the mix is a mistake, fix the call or add the type;
a kind with no such action (`f("abc")` where f does `x.sort()`) is a `kind-mismatch` error at the call; no
calls → list + `kind-guessed`. Types are only for parameters (`var x: list` is an error: a variable's kind is
its value). Calls by text (`code::call_function("f")`) and loop values (`{ i, v -> v.length() }`) are not seen.
`return` without a value just leaves the function; in an event it ends the event (like `break` outside a loop).
## Several return values
Several values: `function divmod(a, b) { return floor(a / b), a % b }` + `var [q, r] = divmod(17, 5)` (or `q, r = divmod(...)`).
Every `return` with a value gives the same number of values. They go through slots `jmcc.return`, `jmcc.return.1`, ...:
a write in the function + a copy at the call per value, no list (a list costs create_list + 2 reads more). `return [a, b]`
is compiled the same way when the file takes the call apart (`var [q, r] = f()`); otherwise it returns a list as before.
The whole value (`var p = divmod(...)`) is the list `[q, r]`. `inline function` with `return a, b`: `var [lo, hi] = mm(a, b)`
writes lo / hi right in its returns (0 extra actions). Taking apart a function that returns one value — `destructure-single`.
## Parameters in edition 2: own per call, by value, ref
Parameters (edition 2, verified on the server): every call has its own parameters and `var`s, so recursion works:
`function fib(n) { if (n < 2) { return n } return fib(n - 1) + fib(n - 2) }` (depth: 500 nested calls work, 5000 stop the
line — "бесконечный цикл без задержки"). A parameter is a VALUE: `x += 1` inside does not change the caller's variable —
return the new value, or declare the parameter `ref` (it IS the caller's variable; the argument must be a variable):
```js
function take(ref coins, price) { if (coins < price) { return false }
  coins -= price
  return true }
if (take(%player%_coins, 50)) { player::message("bought") }
```
A list / map argument is the SAME list: `l.append(x)` inside is seen by the caller (assigning `l = [...]` is not).
Defaults and names: `function f(a, b = 1)` → `f(5)`, `f(a = 2, b = 3)`. A call is one block; an argument that is an
expression, a text with `%` / `${}` or a call result costs +1 (computed into a temp first: the server does not evaluate
arguments). A game value (`f(value::health)`) goes in as is: the function reads it once on entry (verified); for a
`process` it still costs +1.
Game-menu parameter kinds (edition 2): a switch `mode: enum("builder", "off") = "off"` — a call passes one of the texts
(`f("builder")`, another one is an error `enum-param-value`) or omits it; a list over menu cells `points: location[] = []`
(`T` — number, text, location, item, vector, map, any) — a call passes a list. Menu details: `param_info("mode",
element_names = ["Builder", ""], element_icons = [item("stone"), ...])`, `param_info("points", slots = [...])`. NOT
verified on the server: what the body sees for a switch (the element text?) and how empty cells of `T[]` arrive.
`f((coins))` = `f(coins)`. `code::call_function("f")` by name needs `args` (a map with every
parameter) — just write `f(...)`.
Calls inside an expression run before it is computed: in `hits + bump()` the call happens first.
A `process` cannot return a value; `p(a, b)` starts it with its own parameters and without the caller's `var`s.
## Annotations: @icon, @description, @hidden
The in-game function menu: `@icon("minecraft:book")` (an item id, `item("book", "&6Name")` or an `ITEM_…` constant),
`@description("&6line 1", "line 2")`, `@hidden` (not listed in the menu) on the lines before `function` / `process`.
They only set the handler's description / icon / is_hidden (0 actions); without them the JSON is as before. Not for
`inline function` and events; an unknown one (`@Override`) is an error `annotation-unknown`.
## Edition 1 functions
Edition 1 (no `edition 2` line): a function shares the caller's `var`s and parameters; a written parameter is copied back
into the passed variable (unless f writes that variable itself); recursion whose result is used is wrong (warning).
## Row length and module size
Row length (server, verified 2026-12-04): one code row (an event / function / process) loads only if it is
at most 67 blocks in the `jmvcc trace` count — every action, condition, else, loop and closing bracket of a block counts 1
(if/else, else-if, every repeat, nesting depth 8, not, equals with 10 values, controller_* checked; long list arguments
do not matter). 68+ → "Не хватает места для загрузки импортируемого модуля". The compiler handles it for you: by default
it cuts rows at 67 and moves the tail into a helper function `jmcc.fN` (`--max-line <n>` changes the cut, 43 = old jmcc
output, 0 = no cut). The tail is ANOTHER row: in edition 2 the compiler passes it the row's `var`s and parameters (and cuts
before a block whose result the row still needs); in edition 1 a `line var` set before the cut is empty there. `return` / `break` /
`continue` inside it do not leave the original row — in these cases check/compile report an error ("хвост переносится
в функцию jmcc.fN … Вынеси часть кода в отдельную функцию"): split that code into your own function. A module also has a
row limit: about 526 rows on rank Star, 548 on Nova (events + functions + processes, each jmcc.fN counts) — very long
games go into several modules. Do not split code into functions just because it is long (the compiler cuts rows),
but a call costs actions; use functions for reuse and readability. One source line can be several blocks: `||`, `??=` and every call inside a text
(`"${l.length()}"`, `"${f(x)}"`) add blocks (temp variables, extra ifs) — each block is server work.

