Custom Functions
Custom functions let the host application expose Go logic to FQL scripts. Functions can be registered individually or organized into namespaces.
Registered namespace segments and host-function names are case-insensitive in FQL and have one canonical lowercase qualified spelling in registries, documentation, and tooling. Register each symbol once; uppercase and mixed-case registrations are normalized for compatibility.
Registering functions
The most direct way to add functions is WithFunctionsRegistrar. The callback receives a runtime.Namespace where you register functions by arity:
Scripts can then call these functions directly:
Function signatures
Ferret provides typed function signatures for each arity:
| Builder method | Go signature | FQL call |
|---|---|---|
A0() |
func(ctx) (Value, error) |
fn() |
A1() |
func(ctx, arg) (Value, error) |
fn(x) |
A2() |
func(ctx, arg1, arg2) (Value, error) |
fn(x, y) |
A3() |
func(ctx, arg1, arg2, arg3) (Value, error) |
fn(x, y, z) |
A4() |
func(ctx, arg1, arg2, arg3, arg4) (Value, error) |
fn(a, b, c, d) |
Var() |
func(ctx, args ...Value) (Value, error) |
fn(a, b, ...) |
Fixed-arity functions (A0 through A4) automatically validate the argument count. Variadic functions (Var) receive a slice and must validate the count themselves.
Namespaces
Use WithNamespace with a library builder to create a named group of functions:
Scripts call these as:
Namespaces can be nested. A namespace created with ns.Namespace("sub") produces functions accessible as crypto::sub::function_name.
Argument validation
For variadic functions, use the validation helpers from the runtime package to check argument count and types:
Type casting helpers
The runtime package provides generic casting functions that return typed values with clear error messages:
| Helper | Purpose |
|---|---|
CastArg[T](arg, index) |
Cast a single argument to type T |
CastArgAt[T](args, index) |
Cast argument at position in a slice |
CastArgs[T](args) |
Cast all arguments to the same type |
CastArgs2[T1, T2](a, b) |
Cast two arguments to different types |
CastArgs3[T1, T2, T3](a, b, c) |
Cast three arguments to different types |
Arity and type validation
| Helper | Purpose |
|---|---|
ValidateArgs(args, min, max) |
Check argument count is within range |
ValidateArgsType(args, types...) |
Check each argument matches expected type |
ValidateArgType(arg, pos, types...) |
Check a single argument matches one of the expected types |
Merging pre-built function sets
If you have a *runtime.Functions object built separately, merge it into the engine with WithFunctions:
Complete example
A custom namespace that provides string transformation functions: