Skip to main content

Code frameworks

Recipe: a helper function

Share a small calculation inside one rule file.

Goal

Use one capped function instead of repeating math.min.

The change

rules/heal.ts
function capped(value: number, limit: number): number {
  return math.min(value, limit);
}

export function heal(self: ElementRef, amount: number): void {
  const hp: number = element.var(self, "hp") as number;
  const max_hp: number = element.var(self, "max_hp") as number;
  if (hp < max_hp) {
    ledger.set(self, "hp", capped(hp + amount, max_hp));
  }
}
  1. Lines 1-3 A helper has no export.
  2. Line 9 Call it by name from the same file.

A file that exports more than one function is refused, unless every export is declared against that file as an action id or a ledger function id.

functions but only the action heal uses it

A helper may only compute. It cannot call ledger.set or ledger.add, and a helper that writes is refused:

effectful action helpers are not supported until call-target provenance is enforced

Return the value from the helper and write it in the action. The Writing rules page shows two actions that share one helper.

Test it

A helper adds no scenario. The scenarios of the action that uses it prove it.

Next