Expressions
github.com/nsgo-dev/game/pkg/expr parses and evaluates a small, deterministic expression language with named inputs and game functions. It is the one evaluator for data-driven formulas and conditions, console commands and cheat codes, so a balance rule or an unlock condition can live in YAML instead of Go code — which matters on iOS and the web, where content cannot load Go at run time.
e, err := expr.Parse(`hp < 20 && has_item("potion") ? max_hp * 0.25 : hp + 1`, []string{"hp", "max_hp"}, map[string]expr.Func{
"has_item": {
Params: []expr.Kind{expr.KindString},
Result: expr.KindBool,
Call: func(args []expr.Value) (expr.Value, error) {
name, _ := args[0].AsString()
return expr.Bool(inventory.Has(name)), nil
},
},
})
if err != nil { /* a *expr.ParseError with its column */ }
v, err := e.Eval(&expr.Env{
Vars: func(name string) (expr.Value, bool) {
switch name {
case "hp": return expr.Number(player.HP), true
case "max_hp": return expr.Number(player.MaxHP), true
}
return expr.Value{}, false
},
Funcs: funcs,
})
Parse type-checks the whole tree, so a type error is a parse error with its column rather than a failure at run time. Expr is immutable and safe to evaluate concurrently against different Envs. Expr.Number, Bool and String evaluate and require that result kind.
Values and input
There are three kinds: Number (a float64), Bool and String. Names passed to Parse are variables, and they are all numbers; a game reads them through Env.Vars, which returns false for a name it does not have, and the evaluation then fails with ErrUnknownVariable. Functions come from Env.Funcs or from the map passed to Parse, with their parameter and result kinds declared, so Call can assume them.
Built in functions are floor(x), round(x) (half away from zero), abs(x), min(a, b), max(a, b) and clamp(x, low, high). They cannot be replaced by a funcs entry. A clamp whose low bound is above its high bound fails at evaluation.
Operators
From lowest to highest precedence:
| Operators | Meaning |
|---|---|
c ? a : b |
a when c is true, else b; the branches share a kind, and the other branch is not evaluated |
|| |
boolean or, short-circuiting |
&& |
boolean and, short-circuiting |
==, != |
equality of two values of the same kind |
<, <=, >, >= |
numeric comparison |
+, - |
numeric addition and subtraction; string concatenation is deliberately not an operator |
*, /, % |
numeric multiplication, division and remainder by math.Mod |
-, ! |
numeric negation and boolean not |
( ), literals, names, calls |
grouping and primary values |
Numbers are decimal, with an optional fractional part (1, 1.5, .5); strings are single- or double-quoted with \n, \t, \\ and \" escapes; true and false are booleans. Division or remainder by zero fails with ErrDivisionByZero, not infinity.
Limits and determinism
Parse refuses an expression over MaxNodes (4096) or nested deeper than MaxDepth (128) with ErrCostLimit, so a mod's formula cannot make a game parse or evaluate an unbounded tree; there are no loops, assignment or I/O, so the node count also bounds evaluation. Every operation is a single IEEE-754 float64 operation in a fixed order with no fused multiply-add or reassociation, so the same expression and inputs give the same result on every architecture; math.Mod, math.Floor and math.Round define the rounding cases. &&, || and ?: evaluate only the branch they need.
A Parse error is a *ParseError with a Pos column and a message; evaluation errors wrap ErrUnknownVariable, ErrUnknownFunction, ErrDivisionByZero or the error a called function returned, with the column of the node that failed.