# Custom Functions

Write Lua functions, save them to a file, and call them in formulas like built-ins. Custom functions are sandboxed, deterministic, and verifiable.

:::caution[Desktop and CLI only]
Custom functions need the Lua runtime, which is part of the desktop app and the
CLI rather than the calculation engine. A sheet that calls one opens fine in the
[browser app](https://docs.visigrid.app/web/) and computes everything else correctly, but each cell
calling a custom function reads `Unknown function: NAME` there. Nothing is lost
— the formula is intact and the desktop computes it as usual.
:::

```
=ACCRUED_INTEREST(B6, C6, D6)
=HAIRCUT(B6 + E6, F6)
=WEIGHTED_AVG(A1:A10, B1:B10)
```

## Quick Start

### 1. Write your functions

Create `~/.config/visigrid/functions.lua`:

```lua
function ACCRUED_INTEREST(principal, rate, days)
    return principal * rate * days / 365
end

function HAIRCUT(value, haircut_pct)
    return value * (1 - haircut_pct)
end
```

### 2. Launch VisiGrid

Custom functions load automatically on startup. The status bar shows the count:

```
Loaded 2 custom functions
```

### 3. Use them in formulas

Type `=ACCRUED_INTEREST(1000000, 0.0425, 92)` in any cell. It evaluates like a built-in.

### 4. Reload after edits

Edit `functions.lua`, then reload without restarting:

**Command palette** (`Ctrl+Shift+P`) &rarr; **Reload Custom Functions**

## Function Rules

- **Names must be uppercase:** `ACCRUED_INTEREST`, `MY_FUNC`, `TAX2024`
- **Pattern:** `^[A-Z][A-Z0-9_]*$`
- **Built-ins always win:** If your function collides with a built-in (e.g., `SUM`), the built-in is used and you get a warning on reload
- **Return a scalar or a table:** number, string, boolean, nil, or a table that spills into the grid (see [Returning arrays](#returning-arrays))
- **Nil returns empty:** A function returning nil produces an empty cell

## Arguments

### Scalars

Cell references and literals are evaluated before your function sees them. Your function receives plain Lua values.

```lua
function DOUBLE(x)
    return x * 2
end
-- =DOUBLE(A1) passes the value of A1, not a reference
```

### Ranges

Range arguments arrive as a special object with `.n` (count) and `:get(i)` (1-based access).

```lua
function WEIGHTED_AVG(values, weights)
    local sum, wsum = 0, 0
    for i = 1, values.n do
        local v = values:get(i)
        local w = weights:get(i)
        if v ~= nil and w ~= nil then
            sum = sum + v * w
            wsum = wsum + w
        end
    end
    if wsum == 0 then error("total weight is zero") end
    return sum / wsum
end
-- =WEIGHTED_AVG(A1:A10, B1:B10)
```

| API | Returns |
|-----|---------|
| `range.n` | Total cell count |
| `range:get(i)` | Value at 1-based index (nil for empty cells) |

Out-of-bounds access (`:get(0)` or `:get(n+1)`) raises an error, not a silent nil. This catches off-by-one bugs.

## Returning arrays

From 0.32.0 a function may return a table, and the result spills from the calling cell the way a dynamic array does. Two shapes are read, and they mirror how the sheet reads:

```lua
-- A sequence of scalars is a column: one value per row.
function RUNNING_TOTAL(values)
    local out, sum = {}, 0
    for i = 1, values.n do
        sum = sum + (values:get(i) or 0)
        out[i] = sum
    end
    return out
end
-- =RUNNING_TOTAL(B2:B10) fills the cell and the 8 below it

-- A sequence of sequences is rows of columns.
function TOP2(names, scores)
    return {
        { names:get(1), scores:get(1) },
        { names:get(2), scores:get(2) },
    }
end
-- =TOP2(A2:A10, B2:B10) fills a 2×2 block
```

Rules:

- A ragged inner row is padded with empty cells to the widest row, so a missing trailing value never shifts its neighbours.
- Shapes are not mixed. A scalar beside a row (`{1, {2, 3}}`) is an error rather than a guess.
- An empty table is an empty cell.
- Only the sequence part of the table is read; string keys are ignored.
- A result larger than 100,000 cells is refused with `#LUA!`.
- If the spill area is occupied, the cell shows `#SPILL!` and nothing is overwritten, exactly as for a built-in array function.

Spilled values are computed, not stored. The sheet fingerprint covers formulas and constants, so it does not change when `functions.lua` changes; the values a custom function produces, scalar or array, are outside it. If two people must agree on what a sheet computes, they must agree on `functions.lua` as well.

## Error Handling

| Error | Cause |
|-------|-------|
| `#NAME?` | Function not found in `functions.lua` |
| `#LUA!` | Runtime error, sandbox violation, or resource limit |

Errors from arguments propagate automatically. If any argument contains `#DIV/0!` or another error, that error propagates without calling your function.

Use `error()` for intentional errors:

```lua
function POSITIVE_ONLY(x)
    if x == nil then error("requires 1 argument") end
    if x < 0 then error("value must be positive") end
    return x
end
-- =POSITIVE_ONLY(-5) → #LUA! value must be positive
```

## Sandbox

Custom functions run in a locked-down environment. No side effects, no state mutation.

**Available:** `math.*` (except `random`/`randomseed`), `string.*`, `table.*`, `type`, `tonumber`, `tostring`, `pairs`, `ipairs`, `select`, `error`, `pcall`

**Blocked:** `os`, `io`, `debug`, `require`, `load`, `loadfile`, `dofile`, `math.random`

**Global mutation blocked:** Attempting to set a global variable raises `#LUA!`:

```lua
-- This will error, not silently succeed
counter = 0
function COUNT_CALLS()
    counter = counter + 1  -- #LUA! Global state mutation is not allowed
    return counter
end
```

### Resource Limits

| Limit | Value |
|-------|-------|
| Instructions | 10,000,000 per call |
| Wall-clock | 1 second per call |

These are per function call, not per recalc. A function that exceeds either limit returns `#LUA!`.

## Verification

A custom function is deterministic: the same inputs always give the same output. That makes it safe to use in a sheet you verify, but the fingerprint does not cover the function itself.

### What the fingerprint covers

The semantic fingerprint hashes every cell's input and formula text, including `=ACCRUED_INTEREST(B6, C6, D6)`. It does not hash styling, the values formulas produce, or `functions.lua`. Change an input or a formula and the fingerprint changes. Change what `ACCRUED_INTEREST` does in `functions.lua` and it does not.

`functions.lua` lives on your machine and is never saved in the workbook. Someone who opens your file without it sees the values you last saved, and `Unknown function: NAME` in a cell that recalculates. If two people must agree on what a sheet computes, they must agree on `functions.lua` as well.

When the logic has to travel with the file, put it in a `=LUA` cell instead. Its code is formula text, so it is saved in the workbook and covered by the fingerprint:

```
=LUA("return args[1] * args[2] * args[3] / 365", B6, C6, D6)
```

### The verification flow

Run from `examples/custom-functions/` in the VisiGrid repository:

```bash
# 1. Build the sheet and stamp the expected fingerprint into it
vgrid sheet apply portfolio.sheet --lua bond_portfolio.lua --stamp

# 2. Check it at any time
vgrid sheet verify portfolio.sheet
# Status: Verified ✓
#   Fingerprint: v2:35:dbe2f97fc616a0b4

# 3. Rebuild with B6 changed from 1,000,000 to 2,000,000, then check
#    against the fingerprint from step 2
vgrid sheet apply portfolio.sheet --lua bond_portfolio_edited.lua
vgrid sheet verify portfolio.sheet --fingerprint v2:35:dbe2f97fc616a0b4
# Status: Drifted ⚠
#   Expected: v2:35:dbe2f97fc616a0b4
#   Current:  v2:35:554f35abf7604553

# 4. Rebuild from the original script: the fingerprint matches again
vgrid sheet apply portfolio.sheet --lua bond_portfolio.lua
vgrid sheet verify portfolio.sheet --fingerprint v2:35:dbe2f97fc616a0b4
# Status: Verified ✓
```

`verify` exits 0 when the fingerprint matches and 1 when it has drifted, so it works as a CI check. `sheet apply` builds the file from scratch, which is why steps 3 and 4 pass the fingerprint explicitly: a rebuild without `--stamp` carries no stored fingerprint.

Same inputs and formulas, built by the same engine, give the same fingerprint.

## Memoization

Custom functions are automatically memoized within each recalc cycle. If `=ACCRUED_INTEREST(B6, C6, D6)` appears in multiple cells with the same arguments, Lua is called once. Range arguments are fingerprinted using blake3 for efficient cache keys.

## Example: Bond Portfolio

See `examples/custom-functions/` in the VisiGrid repository for a complete worked example:

- `functions.lua` — ACCRUED_INTEREST, HAIRCUT, WEIGHTED_AVG
- `bond_portfolio.lua` — Provenance script building a 3-bond portfolio
- `demo.sh` — Builds the portfolio and walks through its fingerprints