calc

package
v0.0.0-...-904f9c7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package calc implements 公式/计算变量 (calc / formula tags): a derived tag whose live value is an expression evaluated over other tags.

A CalcTag names an Output tag, an Expr, and the Input tags the expression reads. Each Input name is used verbatim as an identifier inside Expr, so the Inputs MUST be simple identifiers — no dots, no paths (e.g. "a", "level", not "plant.a") — because a dot inside an expr expression means field access, not a tag name. The expression is compiled once; whenever any Input changes, the Output tag is recomputed.

Example:

e := calc.NewEngine(db)
e.Add(calc.CalcTag{Output: "avg", Expr: "(a + b) / 2", Inputs: []string{"a", "b"}})
db.SetValue("a", 10.0)
db.SetValue("b", 20.0) // -> tag "avg" == 15

Expressions use github.com/expr-lang/expr. Inputs are fed to the expression as float64 (via core.Value.Float); the result is coerced back to float64 for the Output tag.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CalcTag

type CalcTag struct {
	Output string   // name of the tag that receives the computed value
	Expr   string   // expression over the Input identifiers
	Inputs []string // input tag names, each a simple (dot-free) identifier
}

CalcTag declares one derived tag: Output = Expr evaluated over Inputs.

Inputs are referenced by name as bare identifiers in Expr (e.g. Expr:"(a + b) / 2", Inputs:[]string{"a","b"}) and therefore MUST be simple identifiers without dots.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine wires CalcTags into a core.TagDB: it compiles each expression and keeps the Output tags recomputed as their Inputs change. Add and RemoveAll are safe for concurrent use.

func NewEngine

func NewEngine(tags *core.TagDB) *Engine

NewEngine returns an Engine backed by tags.

func (*Engine) Add

func (e *Engine) Add(ct CalcTag) error

Add compiles ct.Expr once, subscribes to every Input tag, and recomputes the Output tag on Add and on any Input change. It returns the compile error for a malformed expression, in which case nothing is registered.

func (*Engine) RemoveAll

func (e *Engine) RemoveAll()

RemoveAll unsubscribes every calc tag registered on this Engine.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL