script

package
v0.0.0-...-8d5fc3c Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 27 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

+game:group:name=script

Package script runs goscript scripts inside a game.Engine.

Install wires the runtime into an Engine: it builds the script environment from the registered Game Object components, registers the script asset kind (*.gs files, compiled on an asset worker and hot reloaded) and returns the Runtime. System then makes a script a game.Runner:

rt := script.Install(e, script.Config{})
e.AddRunner(game.StageSimulate, script.System("systems/movement.gs"))

A system script defines Init() (run once, when the system is set up and after every reload) and Update(dt) (run every tick with ctx.Time.Dt):

func Update(dt) {
	for e := range world.Query(gfx.Transform, game.Velocity) {
		e.gfx.Transform.Pos += e.game.Velocity.V * dt
	}
}

Scripts reach components as e.group.Name, resources as world.group.Name, and change the world through world.Spawn, world.Despawn and world.Remove, which queue like ctx.Commands. Reading and writing component fields, vector math and query loops allocate nothing.

The guide is doc/guide/engine/scripting.md; the language is doc/design/goscript.md.

Index

Constants

View Source
const AssetKindScript = "script"

AssetKindScript is the asset kind of a Script (a *.gs file): the name a component field carries in its +game:asset:kind=... marker, as Behavior.Script does.

View Source
const DefaultBudget = 1_000_000

DefaultBudget is the budget of one script call when Config.Budget is 0: about a million loop iterations and calls.

View Source
const ParamMarker = "+script:param"

ParamMarker is the marker that describes a parameter, on the line of its var or in its doc comment:

var Speed = 40.0 // +script:param min=0 max=200 step=5 label="Top speed"
View Source
const Suffix = ".gs"

Suffix is the file suffix of script assets.

Variables

View Source
var (
	// Vec2Type is xmath.Vec2 in scripts: two float32, written vec2(x, y) or
	// Vec2{X: x, Y: y}, with + and - between vectors, * and / by a number,
	// unary -, the fields X and Y and the methods Len, Norm, Dot and Angle.
	Vec2Type = &goscript.Type{Name: "Vec2", Inline: true}
	// ColorType is gfx.Color in scripts: rgba(r, g, b, a) with 0..255
	// channels, the int fields R, G, B and A, printed as "#rrggbbaa".
	ColorType = &goscript.Type{Name: "Color", Inline: true}
)

The engine's value types. Vec2 and Color are inline (the whole value is in the 64 bits of a goscript.Value), so making and computing with them allocates nothing. The types are process-wide: their hooks hold no state.

View Source
var (
	CID_Bag      = ecs.RegisterComp[Bag]()
	CID_Behavior = ecs.RegisterComp[Behavior]()
)

Functions

func AsColor

func AsColor(v goscript.Value) (gfx.Color, bool)

AsColor returns the color v holds and true when v is a Color.

func AsVec2

func AsVec2(v goscript.Value) (xmath.Vec2, bool)

AsVec2 returns the vector v holds and true when v is a Vec2.

func Behaviors

func Behaviors() game.Runner

Behaviors returns the game system that runs behaviors: the scripts of the entities with a Behavior that its scene owns (game.Engine.SceneOf). Add it to StageSimulate of the root, and of every scene whose entities have behaviors, where it fits against the other systems:

e.AddRunner(game.StageSimulate, input, script.Behaviors(), game.Wrap(phys))

Every Run, for each behavior entity of the scene, it calls the script's

  • Spawn(self) the first time it runs the entity's script, before its Update;
  • Update(self, dt) with ctx.Time.Dt;
  • Despawn(self) once the entity is dead or lost its Behavior, at the end of a Run; a dead self fails component access, so the function is for the script's own bookkeeping (world.Alive(self) tells which);

and before those, for the tick's collision events whose Self is such an entity, Enter(self, other), Stay(self, other) and Exit(self, other) (collision.Enter, Stay, Exit) and Impact(self, other) (physics.Impact). Every function is optional. Each call runs with the entity's parameters (Behavior.Params over the script's defaults) swapped in.

A script's module (its lowercase top-level vars) is shared by every entity that runs it, in every scene. When the file is reloaded, the next Run loads it again with fresh top-level vars and rebuilds each entity's parameters; Spawn does not run again, and bags keep their data.

Runtime errors go to Config.OnError with the script position and the entity; the entity runs again next tick. Bad parameters and overrides go to game.Config.OnAssetError. Init panics with "script: Install was not called for this Engine" when the Engine has no runtime.

func ColorValue

func ColorValue(c gfx.Color) goscript.Value

ColorValue returns c as a script value.

func Load

func Load(sc *asset.Scope, key string) gfx.ScriptHandle

Load returns the handle for a script key ("enemies/bat.gs") and adds a hold for sc. It never blocks; the script compiles on an asset worker. It panics like asset.Load, also when Install has not run for the Engine that owns sc's server.

func LoadSync

func LoadSync(sc *asset.Scope, key string) (gfx.ScriptHandle, error)

LoadSync is Load followed by loading until the script is compiled or failed, like asset.LoadSync. It blocks: use it for setup, tests and tools.

func ParamSchema

func ParamSchema(params []Param) *god.TypeSchema

ParamSchema returns the GOD schema of a Behavior.Params for a script with params: an object with one property per parameter, in script order (x-editor order), each with the script's default, its label (x-editor name), min, max and step, enums as x-enum. A Vec2 is an object of X and Y, a Color a string of format color. Parameters without a type are left out. Editors draw overrides with it; the runtime does not validate Params against it.

func RegisterResource

func RegisterResource[T any](group, name string)

RegisterResource makes the ECS resource of type T (a struct) reachable from scripts as world.group.Name: reading it gives a reference to the World's resource (nil when it is not set), writing its fields writes the resource, and assigning a value of the type replaces it with a copy (ecs.SetResource). Register resource types before Install, like component types; registering the same type under the same key again is a no-op.

Panics with "script: resource group and name must be identifiers" and "script: resource group:name registered twice with different types".

func System

func System(key string) game.Runner

System returns a game system that runs the script file key. Add it to a stage like any runner:

e.AddRunner(game.StageSimulate, script.System("systems/movement.gs"))

Its Init loads the file into the scene's asset scope and waits until it is compiled, then loads the script (top-level vars and init functions) and calls its Init(), if the script defines one. Every Run calls Update(dt) with ctx.Time.Dt, if defined. When the file is reloaded, the next Run loads the new version, with fresh top-level vars, and calls Init() again.

Errors do not stop the game. A file that fails to load or compile is reported to game.Config.OnAssetError, as any asset is, and the system does nothing until a version compiles. A runtime error in Init or Update goes to Config.OnError, and the system runs Update again on the next tick. Init panics with "script: Install was not called for this Engine" when the Engine has no runtime.

func Vec2Value

func Vec2Value(v xmath.Vec2) goscript.Value

Vec2Value returns v as a script value.

Types

type Bag

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

Bag is a data bag: string-keyed, dynamic script data. As a component it holds one entity's data (e.script.Bag in scripts); as a resource, data scripts share (world.script.Bag). In GOD files it is a JSON object of plain data: numbers, strings, bools, lists and objects.

+game:component

func NewBag

func NewBag(d *goscript.Dict) Bag

NewBag returns a bag holding d, or an empty one when d is nil.

func (Bag) Dict

func (b Bag) Dict() *goscript.Dict

Dict returns the bag's dict, which scripts index. The zero Bag has none and returns nil.

func (Bag) MarshalJSON

func (b Bag) MarshalJSON() ([]byte, error)

MarshalJSON writes the bag as a JSON object. It fails on a value that is not plain data (a function, a struct, a host value) or a key that is not a string, naming the key.

func (*Bag) UnmarshalJSON

func (b *Bag) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a JSON object into a fresh dict: integral numbers become ints, other numbers floats, arrays lists, objects dicts.

type Behavior

type Behavior struct {
	// Script is the *.gs file. The zero handle, a missing or a failed
	// script does nothing until a version compiles.
	//
	// +game:asset:kind=script
	Script gfx.ScriptHandle `json:"-"`
	// Params overrides the script's parameters (its exported top-level
	// vars) for this entity, by name: numbers, strings, bools, Vec2 as
	// {"X": x, "Y": y} and Color as "#rrggbbaa". A parameter left out keeps
	// the script's default. A name the script does not declare, or a value
	// of the wrong type, is reported to game.Config.OnAssetError and the
	// default is used.
	Params map[string]any
	// contains filtered or unexported fields
}

Behavior gives an entity a script: the behavior runner (Behaviors) calls the script's Spawn(self), Update(self, dt), Despawn(self) and event handlers for it. An entity has at most one behavior.

+game:component

type Config

type Config struct {
	// OnError receives compile errors of scripts that fail to reload and
	// runtime errors of script calls, with the script position. Nil logs
	// them with the log package.
	OnError func(error)
	// Budget bounds the loop iterations and calls of one script call (see
	// goscript.Options.Budget). 0 means DefaultBudget; a negative value
	// means unlimited.
	Budget int64
	// Output receives print output. Nil discards it.
	Output io.Writer
	// Env, when set, is called with the script environment after the
	// engine's own functions and types are in it, so a game can add its own
	// (env.Func("game.Score", ...)). It runs once, in Install.
	Env func(env *goscript.Env)
}

Config configures Install.

type Param

type Param struct {
	// Name is the var's name.
	Name string
	// Type is the annotation, or the kind of the default when the var has
	// none.
	Type ParamType
	// Default is the value the script's initializer gave the var.
	Default goscript.Value
	// Min, Max and Step bound a number in the editor (marker min=, max=,
	// step=); nil when not set.
	Min, Max, Step *float64
	// Label is the editor's label (marker label="..."); empty means Name.
	Label string
	// Enum names the values 0, 1, ... of an int parameter (marker
	// enum=idle,chase,flee); an override may use a name instead of the
	// number.
	Enum []string
	// Pos is where the var is declared.
	Pos token.Position
}

Param is a parameter of a behavior script: an exported top-level var, which the editor shows on each entity that uses the script and which each entity may override (Behavior.Params).

type ParamType

type ParamType string

ParamType is the type of a behavior parameter.

const (
	ParamInt    ParamType = "int"
	ParamFloat  ParamType = "float"
	ParamBool   ParamType = "bool"
	ParamString ParamType = "string"
	ParamVec2   ParamType = "Vec2"
	ParamColor  ParamType = "Color"
)

Parameter types.

type Runtime

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

Runtime is the script runtime of one Engine: the script environment, the VM every script of the Engine runs on, and the per-call state. Get it from Install or Of. Like the Engine it is single-goroutine.

func Install

func Install(e *game.Engine, cfg Config) *Runtime

Install builds the script runtime of e and returns it. It registers the script asset type on e's asset server and on e's library (when it has one), and builds the script environment from the Game Object components registered at this point (god.Components) and the resource types registered with RegisterResource: register game types before calling it, as with every Install.

Panics with "script: Install called twice for this Engine".

func Of

func Of(w *ecs.World) *Runtime

Of returns the runtime installed on the Engine that owns w, or nil.

func (*Runtime) Env

func (rt *Runtime) Env() *goscript.Env

Env returns the script environment. Scripts compiled against it can run on this runtime only. Do not change it after the first script compiled.

func (*Runtime) ParamsOf

func (rt *Runtime) ParamsOf(prog *goscript.Program) ([]Param, error)

ParamsOf loads prog into a throwaway module and describes its parameters, as a behavior runner would: for tools such as the level editor, which show a script's parameters before anything runs it. The module's top-level initializers run outside a script call, so one that touches the world (world.Spawn, a component) fails with an error instead of changing the game. Problems with markers or types are returned joined, next to the parameters that could be described.

func (*Runtime) ScriptParams

func (rt *Runtime) ScriptParams(h gfx.ScriptHandle) []Param

ScriptParams returns the parameters of the behavior script h as loaded by a behavior runner: name, type, default and editor hints. It returns nil until a runner has run an entity with the script.

func (*Runtime) VM

func (rt *Runtime) VM() *goscript.VM

VM returns the VM every script of the runtime runs on.

type Script

type Script struct {
	// Program is the compiled script. It is immutable and shared by every
	// system that runs the file.
	Program *goscript.Program
}

Script is a compiled script file (*.gs): the asset type that System loads. Compiling happens on an asset worker, so a big script never stalls a tick, and hot reload replaces the value when the file changes: a file that fails to compile keeps the last good version and reports the error (with file:line:col) to game.Config.OnAssetError, like any asset that fails to reload.

The placeholder (a missing or failed first load) has a nil Program.

type Store

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

Store resolves gfx.ScriptHandle values. Get one with StoreOf. It is a small value; copy it freely.

func StoreOf

func StoreOf(srv *asset.Server) Store

StoreOf returns the script store of srv. It panics like asset.StoreOf if Install has not run for the Engine that owns srv.

func (Store) Err

func (s Store) Err(h gfx.ScriptHandle) error

Err returns why the script failed to load or compile, or nil.

func (Store) Generic

func (s Store) Generic() *asset.Store[Script]

Generic returns the underlying generic store.

func (Store) Get

func (s Store) Get(h gfx.ScriptHandle) *Script

Get returns the script, or the placeholder (a nil Program); see asset.Store.Get for the pointer validity rule. It does not allocate.

func (Store) Key

func (s Store) Key(h gfx.ScriptHandle) asset.Key

Key returns the key h was loaded from, or the zero Key for a zero or stale handle.

func (Store) Lookup

func (s Store) Lookup(h gfx.ScriptHandle) (*Script, asset.State)

Lookup is Get plus the load state; see asset.Store.Lookup.

func (Store) Ready

func (s Store) Ready(h gfx.ScriptHandle) bool

Ready reports whether h refers to a compiled script.

func (Store) Version

func (s Store) Version(h gfx.ScriptHandle) uint32

Version returns the script's version, which a hot reload increments; see asset.Store.Version.

Jump to

Keyboard shortcuts

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