{"modulePath":"github.com/weakpixel/engine","version":"v0.0.0-20261205071607-94fff0387040","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package goscript\n\nPackage goscript is the core of goscript, the scripting language of the Weakpixel engine: a small, dynamically typed language with Go syntax, compiled to bytecode and run on a register VM.\n\nA script file is valid Go syntax without a package clause and without imports. It holds top-level var, const, struct type and func declarations; parameters and variables need no types, and a type, where written, is checked at run time. Lists and dicts are written list{1, 2} and dict{\"k\": v}:\n\n\tconst limit = 100\n\n\tvar calls = 0\n\n\tfunc fib(n) {\n\t\tcalls++\n\t\tif n \u003c 2 {\n\t\t\treturn n\n\t\t}\n\t\treturn fib(n-1) + fib(n-2)\n\t}\n\nUse it in three steps: [Compile](#Compile) turns source into an immutable [Program](#Program), [VM.Load](#VM.Load) instantiates a [Module](#Module) (its globals) and runs the top-level initializers, and [Module.Func](#Module.Func) looks up a function to call with [Func.Call](#Func.Call). Calls, arithmetic, loops, recursion and access to existing lists, dicts and structs allocate nothing once the VM's register file has grown to the deepest call; that is the point of the package, so it can run inside a game tick. [Options.Budget](#Options.Budget) stops a runaway script.\n\nThe host decides what scripts can reach: it registers functions ([Env.Func](#Env.Func), called with a [Call](#Call) that aliases the VM's registers) and value types ([Env.Type](#Env.Type): inline types such as a vector kept in 64 bits, or heap types wrapping a Go pointer) in an [Env](#Env) passed to [Compile](#Compile). Host functions may call script functions back. See the package example.\n\nThe package depends on the standard library only (go/parser parses the source) and knows nothing about the engine; the engine integration lives elsewhere. A VM, and every Module and Func loaded into it, is meant for one goroutine, like the engine's World.\n\nDesign and status: doc/design/goscript.md.\n\n## Functions\n\n```go\nfunc Equal(a, b Value) bool\n```\nEqual reports whether a == b under the script's == operator: same kind and same value; an int and a float compare by numeric value, like Go's untyped constants; strings by content; functions by identity.\n\n```go\nfunc HostPointer[T any](t *Type, v Value) (*T, bool)\n```\nHostPointer returns the pointer of v and true when v is a value of the heap type t. T must be the type the values of t were made from; the pointer stays valid for as long as the host keeps it alive.\n\n## Types\n\n```go\ntype Call struct {\n\t// contains filtered or unexported fields\n}\n```\nCall is one call of a host function. The VM reuses Calls: do not keep a \\*Call, or the slice from Args, after the function returns.\n\n```go\nfunc (c *Call) Arg(i int) Value\n```\nArg returns argument i, or nil when there are fewer arguments.\n\n```go\nfunc (c *Call) Args() []Value\n```\nArgs returns the arguments. The slice aliases the VM's registers.\n\n```go\nfunc (c *Call) Bool(i int) (bool, error)\n```\nBool returns argument i as a bool.\n\n```go\nfunc (c *Call) Float(i int) (float64, error)\n```\nFloat returns argument i as a float; an int converts.\n\n```go\nfunc (c *Call) Int(i int) (int64, error)\n```\nInt returns argument i as an int, or an error naming the function and the argument when it is missing or not an int.\n\n```go\nfunc (c *Call) Return(results ...Value)\n```\nReturn sets the results; it replaces earlier ones. It panics past eight results.\n\n```go\nfunc (c *Call) String(i int) (string, error)\n```\nString returns argument i as a string.\n\n```go\nfunc (c *Call) VM() *VM\n```\nVM returns the VM running the call, for reentrant calls of script functions ([Func.Call](#Func.Call) works from inside a host function).\n\n```go\ntype Dict struct {\n\t// contains filtered or unexported fields\n}\n```\nDict is a script dict: keys to values, iterated in insertion order so that scripts and replays are deterministic. Scripts write dict{\"k\": v} and share dicts by reference.\n\nKeys are bools, ints, floats, strings, inline host values and heap objects (by identity). A float key with an integral value is the same key as that int, matching 1 == 1.0.\n\n```go\nfunc NewDict() *Dict\n```\nNewDict returns an empty dict.\n\n```go\nfunc (d *Dict) All() iter.Seq2[Value, Value]\n```\nAll iterates over the entries in insertion order.\n\n```go\nfunc (d *Dict) Delete(key Value)\n```\nDelete removes key; a missing key is no error, as in Go.\n\n```go\nfunc (d *Dict) Get(key Value) (Value, bool)\n```\nGet returns the value for key and whether the key is present. A key that cannot be a dict key is reported as absent.\n\n```go\nfunc (d *Dict) Len() int\n```\nLen returns the number of entries.\n\n```go\nfunc (d *Dict) Set(key, value Value) bool\n```\nSet stores value under key. It returns false, storing nothing, when key cannot be a dict key (nil, NaN). Adding a key may allocate.\n\n```go\nfunc (d *Dict) Value() Value\n```\nValue returns d as a Value. A nil d gives nil.\n\n```go\ntype Env struct {\n\t// contains filtered or unexported fields\n}\n```\nEnv is what the host offers scripts: functions, grouped in namespaces by dotted names, and value types. [Compile](#Compile) resolves every name of a script against it, so a misspelled host name is a compile error. Build an Env before compiling and do not change it while a Program compiled with it is loaded.\n\n```go\nfunc NewEnv() *Env\n```\nNewEnv returns an empty Env.\n\n```go\nfunc (e *Env) FieldType(t *Type)\n```\nFieldType registers t for field and method access only: values of t that host functions or fields return work in scripts, but scripts cannot name t (no annotation, literal or type value), so its name only appears in messages and need not be unique. Use it for the struct types nested in a host type's fields. Dotted field names make groups as for [Env.Type](#Env.Type).\n\n```go\nfunc (e *Env) Func(name string, fn func(*Call) error)\n```\nFunc registers fn under name: \"clamp\" is called as clamp(x), and \"sound.Play\" as sound.Play(key), which makes sound a namespace. It panics when name is not an identifier or two joined by a dot, when it is already registered, or when it collides with a namespace.\n\n```go\nfunc (e *Env) Global(name string, v Value)\n```\nGlobal registers a read-only global: scripts read name as v, call its methods and read its fields (world.Spawn(...), world.game.Settings). It panics when name is not an identifier or is already a host function, type, global or namespace.\n\n```go\nfunc (e *Env) Type(t *Type)\n```\nType registers t, making its name usable in type annotations and, as a value, in expressions ([TypeOf](#TypeOf) reads it back). A dotted name such as \"gfx.Transform\" puts the type in namespace gfx, like a dotted function. A field whose name is dotted, such as \"gfx.Transform\", makes its first part a reserved group: the compiler reads x.gfx.Transform as that one field, and a script may not declare a variable, parameter or struct field named gfx.\n\nIt panics when t's name or a field name is not an identifier or ns.Name, when the name is already registered here or collides with a namespace, or when the process has more than 8191 host types.\n\n```go\ntype Error struct {\n\tPos token.Position\n\tMsg string\n}\n```\nError is a compile error: a problem in the script's source, at a position of the original file.\n\n```go\nfunc (e *Error) Error() string\n```\n\n```go\ntype Field struct {\n\t// Get returns the field of v.\n\tGet func(vm *VM, v Value) (Value, error)\n\t// Set returns v with the field set to x: a new value for an inline\n\t// type, the same pointer after storing for a heap type. Nil makes the\n\t// field read-only.\n\tSet func(vm *VM, v, x Value) (Value, error)\n}\n```\nField is a field of a host [Type](#Type). The hooks get the VM running the script, so a host that keeps state per VM ([VM.SetHost](#VM.SetHost)) can reach it; they must not call script functions. An error stops the script with a runtime error at the access.\n\n```go\ntype Func struct {\n\t// contains filtered or unexported fields\n}\n```\nFunc is a function value: a script function of a [Module](#Module), a closure, or a host function registered with [Env.Func](#Env.Func).\n\n```go\nfunc (f *Func) Call(args, results []Value) (int, error)\n```\nCall runs f with args and copies its results into results. It returns how many results f returned; results beyond len(results) are dropped, and entries past the returned count are left as they were. args and results stay owned by the caller and are not retained, so a call allocates nothing once the VM's register file is large enough.\n\nA script error is returned as a [\\*RuntimeError](#RuntimeError) and leaves the VM usable. A wrong number of arguments is such an error too.\n\nCall may be used from inside a host function ([Call.VM](#Call.VM)): the call runs on top of the running one and shares its instruction budget.\n\nCall panics when f is nil.\n\n```go\nfunc (f *Func) Name() string\n```\nName returns the function's name as declared (\"func\" for a closure).\n\n```go\nfunc (f *Func) Value() Value\n```\nValue returns f as a Value, to pass a function to a script.\n\n```go\ntype Kind uint8\n```\nKind is the dynamic type of a [Value](#Value).\n\n```go\nconst (\n\tKindNil Kind = iota\n\tKindBool\n\tKindInt\n\tKindFloat\n\tKindString\n\tKindFunc\n\tKindList\n\tKindDict\n\tKindStruct // a script struct\n\tKindHost   // a value of a host-defined [Type]\n\n)\n```\nThe kinds of values. The zero Value is KindNil.\n\n```go\nfunc (k Kind) String() string\n```\nString returns the kind's name as scripts and error messages spell it.\n\n```go\ntype List struct {\n\t// contains filtered or unexported fields\n}\n```\nList is a script list: an ordered, growable sequence of values. Scripts write list{1, 2} and share lists by reference. A host may create lists, read them and change them, from the goroutine that runs the VM.\n\n```go\nfunc NewList(items ...Value) *List\n```\nNewList returns a list holding a copy of items.\n\n```go\nfunc (l *List) All() iter.Seq2[int, Value]\n```\nAll iterates over the items with their indexes.\n\n```go\nfunc (l *List) Append(items ...Value)\n```\nAppend adds items at the end; it allocates only when the list grows past its capacity.\n\n```go\nfunc (l *List) At(i int) Value\n```\nAt returns item i. It panics when i is out of range.\n\n```go\nfunc (l *List) Len() int\n```\nLen returns the number of items.\n\n```go\nfunc (l *List) Set(i int, v Value)\n```\nSet replaces item i. It panics when i is out of range.\n\n```go\nfunc (l *List) Value() Value\n```\nValue returns l as a Value. A nil l gives nil.\n\n```go\ntype Module struct {\n\t// contains filtered or unexported fields\n}\n```\nModule is a [Program](#Program) loaded into a [VM](#VM): the program's code with its own globals. Loading the same Program twice gives two independent Modules.\n\n```go\nfunc (m *Module) CopyParams(dst []Value) []Value\n```\nCopyParams copies the current values of the script's parameters into dst, in the order of [Program.Params](#Program.Params), and returns dst; dst must have room for them. After [VM.Load](#VM.Load) these are the defaults the initializers set.\n\nPanics with \"goscript: CopyParams: want \\\u003cn\u003e values\" when len(dst) is not the number of parameters.\n\n```go\nfunc (m *Module) Func(name string) *Func\n```\nFunc returns the top-level function name, or nil when the script declares no function by that name.\n\n```go\nfunc (m *Module) Global(name string) (Value, bool)\n```\nGlobal returns the current value of the top-level var or func name, and false when the script declares no such global.\n\n```go\nfunc (m *Module) Program() *Program\n```\nProgram returns the Program m was loaded from.\n\n```go\nfunc (m *Module) SetGlobal(name string, v Value) bool\n```\nSetGlobal sets the top-level var name and reports whether the script declares it. Functions cannot be replaced.\n\n```go\nfunc (m *Module) SwapParams(vals []Value)\n```\nSwapParams exchanges the values of the script's parameters with vals, in the order of [Program.Params](#Program.Params): afterwards the parameters hold what vals held, and vals holds their previous values. Calling it twice restores both. It allocates nothing.\n\nA host running one Module for many objects keeps a slice per object and swaps it in before calling into the script and out after it, so code reading a parameter sees the object's value and writes to it stay with the object. Closures called later see whatever slice is swapped in then.\n\nPanics with \"goscript: SwapParams: want \\\u003cn\u003e values\" when len(vals) is not the number of parameters.\n\n```go\ntype Op uint8\n```\nOp is an arithmetic operator handed to [Type.Binary](#Type.Binary).\n\n```go\nconst (\n\tOpAdd Op = iota\n\tOpSub\n\tOpMul\n\tOpDiv\n\tOpMod\n\tOpNeg // unary minus: b is nil\n)\n```\nThe operators a host type can implement.\n\n```go\nfunc (o Op) String() string\n```\nString returns the operator as scripts write it, such as \"+\".\n\n```go\ntype Options struct {\n\t// Output receives what the builtin print writes. Nil means io.Discard.\n\tOutput io.Writer\n\t// MaxCallDepth bounds nested script calls; a deeper call is a runtime\n\t// error (\"stack overflow\"). Zero means 1000.\n\tMaxCallDepth int\n\t// Budget bounds the work of one call from the host: every loop\n\t// iteration (backward jump) and every call uses one unit, and a call\n\t// that runs out stops with a runtime error (\"budget exhausted\"), so a\n\t// runaway loop cannot freeze the game. Calls a host function makes\n\t// from inside a call share its budget. Zero means unlimited.\n\tBudget int64\n}\n```\nOptions configures a [VM](#VM).\n\n```go\ntype Param struct {\n\t// Name is the var's name.\n\tName string\n\t// Type is the var's type annotation as written (\"float\", \"Vec2\"),\n\t// or \"\" when it has none.\n\tType string\n\t// Comment is the text of the var's doc and line comments, without the\n\t// comment markers, doc comment first, one line per comment line. The\n\t// host reads its own markers from it.\n\tComment string\n\t// Pos is where the var is declared.\n\tPos token.Position\n\t// contains filtered or unexported fields\n}\n```\nParam is an exported top-level var of a script: a value the host may set per use of the script. A host that runs one script for many objects (an engine running the same behavior on many entities) keeps a value slice per object and swaps it in around each call with [Module.SwapParams](#Module.SwapParams), so the script reads its parameters as ordinary globals.\n\n```go\ntype Program struct {\n\t// contains filtered or unexported fields\n}\n```\nProgram is a compiled script. It is immutable and may be loaded into any number of VMs ([VM.Load](#VM.Load)); each load gets its own globals.\n\n```go\nfunc Compile(name string, src []byte, env *Env) (*Program, error)\n```\nCompile parses and compiles a script against env, the host's functions and types (nil for none). name is used in positions (\"name:line:col\") and errors. All problems the compiler finds are returned together as one error (errors.Join of [\\*Error](#Error) values).\n\n```go\nfunc (p *Program) Name() string\n```\nName returns the script name given to [Compile](#Compile).\n\n```go\nfunc (p *Program) Params() []Param\n```\nParams returns the script's parameters, its exported top-level vars, in source order. The slice is shared: do not change it.\n\n```go\ntype RuntimeError struct {\n\t// Pos is where the failing instruction came from.\n\tPos token.Position\n\tMsg string\n\t// Trace lists the active calls when the error happened, innermost\n\t// first; Trace[0].Pos == Pos.\n\tTrace []TraceEntry\n}\n```\nRuntimeError is an error a script raised while running: an operation on the wrong kinds, an integer division by zero, a call with the wrong number of arguments, a stack overflow. The VM unwinds the failed call and stays usable.\n\n```go\nfunc (e *RuntimeError) Error() string\n```\n\n```go\ntype Struct struct {\n\t// contains filtered or unexported fields\n}\n```\nStruct is a script struct value. Structs are references: T{} and \u0026T{} both make one, and assignment shares it.\n\n```go\ntype TraceEntry struct {\n\tFunc string\n\tPos  token.Position\n}\n```\nTraceEntry is one call of a [RuntimeError](#RuntimeError)'s trace.\n\n```go\ntype Type struct {\n\t// Name is how scripts write the type in annotations and how errors\n\t// name it. It must be a Go identifier.\n\tName string\n\t// Inline selects the 64-bit inline representation ([Type.Make],\n\t// [Type.Bits]); otherwise values are pointers ([HostValue]).\n\tInline bool\n\t// Fields are read as v.Name and written as v.Name = x.\n\tFields map[string]Field\n\t// Methods are called as v.Name(args); the receiver is argument 0.\n\tMethods map[string]func(*Call) error\n\t// Binary implements the arithmetic operators where one operand has\n\t// this type (the other may be any value, as in v * 2). It returns an\n\t// error for an operand it does not support.\n\tBinary func(op Op, a, b Value) (Value, error)\n\t// Equal replaces bitwise (inline) or pointer (heap) equality.\n\tEqual func(a, b Value) bool\n\t// String formats a value for print; nil prints the type's name.\n\tString func(v Value) string\n\t// New makes a value from a composite literal, T{A: 1, B: x}. The call's\n\t// arguments are the literal's field names (as strings) and values,\n\t// alternating, in source order; the compiler has checked that every\n\t// name is a field of the type. Nil makes literals of the type a compile\n\t// error. It may allocate: a literal makes a value.\n\tNew func(c *Call) error\n\t// Range and Next make the values rangeable: for k, v := range x. Range,\n\t// if set, returns the starting state of a loop over v (otherwise it is\n\t// nil); Next is called with v and a pointer to the state before every\n\t// step and returns the step's key and value, or ok false when the loop\n\t// is done. The VM keeps the state in a register, so a loop whose hooks\n\t// do not allocate allocates nothing. A loop left with break or return\n\t// gets no further call. Nil Next makes ranging over the type an error.\n\t// Like the Field hooks, they get the VM and must not call scripts.\n\tRange func(vm *VM, v Value) (state Value, err error)\n\tNext  func(vm *VM, v Value, state *Value) (key, value Value, ok bool, err error)\n\t// contains filtered or unexported fields\n}\n```\nType is a value type defined by the host, such as a vector, a color or a handle to a Go object. Register it with [Env.Type](#Env.Type) before compiling a script that names it.\n\nAn inline type keeps its whole value in 64 bits (two float32, a packed color): making, copying and passing its values never allocates. A heap type points at a Go value of the host ([HostValue](#HostValue), [HostPointer](#HostPointer)).\n\nThe hooks are optional. They run on the VM's goroutine and must not keep the Values of a [Call](#Call) beyond it.\n\n```go\nfunc HostTypeOf(v Value) (*Type, bool)\n```\nHostTypeOf returns the host type of v and true when v is a host value (inline or heap).\n\n```go\nfunc TypeOf(v Value) (*Type, bool)\n```\nTypeOf returns the host type that v names and true when v is a type name used as a value, such as gfx.Sprite in world.Remove(e, gfx.Sprite).\n\n```go\nfunc (t *Type) Bits(v Value) (uint64, bool)\n```\nBits returns the bits of v and true when v is an inline value of t.\n\n```go\nfunc (t *Type) Deref(v Value) (unsafe.Pointer, uint32, bool)\n```\nDeref returns the pointer and the extra bits of v and true when v is a value of the heap type t (made by Ref or HostValue).\n\n```go\nfunc (t *Type) Make(bits uint64) Value\n```\nMake returns an inline value of t with the given bits. It panics when t is not inline or not registered with an [Env](#Env).\n\n```go\nfunc (t *Type) Ref(p unsafe.Pointer, extra uint32) Value\n```\nRef returns a value of the heap type t pointing at p, with 32 bits of host data carried in the value itself, so a host can check it on every access without a lookup (a generation, an epoch). p must point into memory the garbage collector knows (a Go allocation, possibly into the middle of it). A nil p gives nil. It panics like [HostValue](#HostValue).\n\nUse it instead of HostValue when the values point into memory the host owns as raw bytes, such as a field of a struct held by reference.\n\n```go\ntype VM struct {\n\t// contains filtered or unexported fields\n}\n```\nVM runs compiled scripts. It owns one register file and one frame stack, shared by every [Module](#Module) loaded into it. Both grow (by doubling) only when a call goes deeper than any call before, so steady-state calls allocate nothing.\n\nA VM is not safe for concurrent use: use it, and its Modules and Funcs, from one goroutine.\n\n```go\nfunc New(opts Options) *VM\n```\nNew returns a VM configured by opts.\n\n```go\nfunc (vm *VM) Host() any\n```\nHost returns what SetHost stored, or nil.\n\n```go\nfunc (vm *VM) Load(prog *Program) (*Module, error)\n```\nLoad instantiates prog in vm: it allocates the globals, then runs the top-level var initializers (in dependency order) and the init functions (in source order). An error is the first initializer's [\\*RuntimeError](#RuntimeError); the Module is not returned then.\n\n```go\nfunc (vm *VM) SetHost(h any)\n```\nSetHost stores the host's own state for this VM, such as the engine runtime that loaded its scripts. Host hooks reach it with [VM.Host](#VM.Host).\n\n```go\ntype Value struct {\n\t// contains filtered or unexported fields\n}\n```\nValue is one script value. It is two machine words, so it is copied, stored in registers and passed to and from the host without allocating.\n\nLayout (why: a single NaN-boxed uint64 would hide pointers from Go's garbage collector, so the pointer gets its own word):\n\n  - nil: p == nil, u == 0. The zero Value is nil.\n  - bool, int, float, builtin: p points at the kind's entry of scalarTags (a static sentinel, so the GC ignores it) and u holds the bits.\n  - string: p is the string's data pointer (or emptyString for \"\"), u the length. u's top bit is clear.\n  - inline host values: p points at the type's entry of hostTags, u holds the bits the host chose (a float32 vector, a packed color).\n  - heap objects (functions, lists, dicts, structs, cells, host objects): p points at the object, u is heapTag | kind, plus for host objects the host type's index in bits 8 to 23 and 32 bits of host data in bits 24 to 55 (see Type.Ref).\n\nKind tells them apart in this order: p == nil, p inside scalarTags, p inside hostTags, u's top bit; what is left is a string.\n\n```go\nfunc Bool(b bool) Value\n```\nBool returns a bool Value.\n\n```go\nfunc Float(f float64) Value\n```\nFloat returns a float Value (float64).\n\n```go\nfunc HostValue[T any](t *Type, p *T) Value\n```\nHostValue returns p as a value of the heap type t. A nil p gives nil. It panics when t is inline or not registered with an [Env](#Env).\n\n```go\nfunc Int(i int64) Value\n```\nInt returns an int Value (int64, like the script type int).\n\n```go\nfunc Nil() Value\n```\nNil returns the nil Value (the zero Value).\n\n```go\nfunc String(s string) Value\n```\nString returns a string Value. It does not copy s: the Value keeps s's bytes alive, which is safe because Go strings are immutable.\n\n```go\nfunc (v Value) AsBool() (b, ok bool)\n```\nAsBool returns v's bool and true, or false and false when v is not a bool.\n\n```go\nfunc (v Value) AsDict() (*Dict, bool)\n```\nAsDict returns v's dict and true, or nil and false when v is not a dict.\n\n```go\nfunc (v Value) AsFloat() (float64, bool)\n```\nAsFloat returns v's float and true, or 0 and false when v is not a float. An int is not converted; use [Value.Number](#Value.Number) for either.\n\n```go\nfunc (v Value) AsFunc() (*Func, bool)\n```\nAsFunc returns v's function and true when v is a script or host function value (not a builtin).\n\n```go\nfunc (v Value) AsInt() (int64, bool)\n```\nAsInt returns v's int and true, or 0 and false when v is not an int. A float is not converted.\n\n```go\nfunc (v Value) AsList() (*List, bool)\n```\nAsList returns v's list and true, or nil and false when v is not a list.\n\n```go\nfunc (v Value) AsString() (string, bool)\n```\nAsString returns v's string and true, or \"\" and false when v is not a string. It does not copy.\n\n```go\nfunc (v Value) IsNil() bool\n```\nIsNil reports whether v is nil.\n\n```go\nfunc (v Value) Kind() Kind\n```\nKind returns v's dynamic type. Builtin functions report KindFunc.\n\n```go\nfunc (v Value) Number() (float64, bool)\n```\nNumber returns v as a float64 when v is an int or a float.\n\n```go\nfunc (v Value) String() string\n```\nString formats v the way the script builtin print does: nil, true/false, Go's formatting of int64 and float64 ('g', shortest), strings as they are, functions as func name, lists as \\[a b], dicts as map\\[k:v], structs as T{F: v}, host values by their type's String. It allocates.\n\n","path":"github.com/weakpixel/engine/goscript","name":"goscript","synopsis":"Package goscript is the core of goscript, the scripting language of the Weakpixel engine: a small, dynamically typed language with Go syntax, compiled to bytecode and run on a register VM.","isRedistributable":true}
