# Keywords and builtins

> Aego 0.12.5 · development; docs build `4a32b816933e02930662f6a443cb25abe6050d090c55e237cbff5c44ae9b25f8`. [Build manifest](/docs-build.json).

Every keyword, builtin type and builtin function of Aego Script. Hover in the script editor shows the same text.

Run it: `append`, `len`, `start`, `yield frames`, `signal`, `Emit`, `Connect` and `Disconnect` in one script.

```aes run
package demo

import "aego/log"

script Builtins {
    signal Counted(n int)

    var words []string
    var conn Connection
    var count Coroutine

    func Ready() {
        words = append(words, "yield")
        words = append(words, "start")
        words = append(words, "signal")
        conn = Counted.Connect(OnCounted)
        count = start Count()
        log.Info(string(len(words)) + " words, running: " + string(count.Running()))
    }

    func Count() coroutine {
        for i := 0; i < len(words); i++ {
            Counted.Emit(i)
            yield frames(10)
        }
        conn.Disconnect()
        log.Info("connected after Disconnect: " + string(conn.Connected()))
    }

    func OnCounted(n int) {
        log.Info("word " + string(n) + ": " + words[n] + " (" + string(len(words[n])) + " bytes)")
    }
}
```

## package

package names the package of this file. It must equal the directory name under scripts/; all files in one directory share it.

## import

import makes a script package or an engine module available by the last element of its path.

```aes
import (
	"aego/input"
	"mygame/combat"
)
```

## script

script declares a stateful type that attaches to scene nodes. A node holds at most one instance of each script type.
var fields are runtime state; @export fields are saved in the scene and shown in the Inspector.

```aes
script Mover {
	@export var Speed float = 200
	func Update(dt float) {
	}
}
```

## type

type declares a struct. Structs are values: assignment and passing copy them.

```aes
type Stats struct {
	Hp    int
	Armor float
}
```

## struct

struct lists the fields of a type declaration. Fields may be scalars, vectors, references, enums, slices or other structs.

## enum

enum declares named int constants used as Name.Member. A switch on an enum must cover every member or have a default.

```aes
enum State {
	Idle
	Run
}
```

## var

var declares a variable with an explicit type and an optional value. Inside a script it declares a field.

```aes
var hits []int
var speed float = 1.5
```

## const

const declares a compile-time constant of type bool, int, float, string or enum. Packages hold constants only, never mutable variables.

```aes
const MaxSpeed float = 600
```

## func

func declares a function. Package functions see no script state; functions inside a script are methods and can use node and the fields.

```aes
func clamp01(x float) float {
	return math.Clamp(x, 0, 1)
}
```

## return

return ends the function, with a value when the function declares a result. Such a function must return on every path.

## if

if runs a block when the bool condition is true. No parentheses around the condition.

```aes
if hp <= 0 {
	die()
} else if hp < 10 {
	flee()
}
```

## else

else runs when the preceding if condition is false. It must stay on the line of the closing brace: } else {

## for

for is the only loop: for cond {}, for init; cond; post {} or for {} for an endless loop.

```aes
for i := 0; i < len(items); i++ {
}
```

## switch

switch compares a value with each case and runs the first match. There is no fallthrough.

```aes
switch state {
case State.Idle:
case State.Run, State.Walk:
default:
}
```

## case

case lists one or more values for a switch branch.

## default

default runs when no case of the switch matches.

## break

break leaves the innermost for loop or switch.

## continue

continue jumps to the next iteration of the innermost for loop.

## true

true is the bool constant for yes.

## false

false is the bool constant for no.

## nil

nil is the empty reference. Only NodeRef, AssetRef and ComponentRef can be nil; reading through nil faults with AES6004.

```aes
if Target != nil {
}
```

## @export

@export saves the field in the scene and shows it in the Inspector.
Arguments: min, max, step (numbers only), unit, display, tip, category.

```aes
@export(min=0, max=600, unit="px/s")
var Speed float = 220
```

## @former

@former lists old names so scenes saved before a rename still load; the scene is rewritten with the new name on save.

```aes
@former("Velocity")
@export var Speed float
```

## @hide

@hide keeps the script out of the Add Script menu. Existing attachments keep working.

## Ready

Ready runs once after every instance in the scene exists and references are resolved, in scene pre-order.

```aes
func Ready() {
}
```

## Update

Update runs every frame. dt is the frame time in seconds.

```aes
func Update(dt float) {
}
```

## FixedUpdate

FixedUpdate runs every fixed step, before physics. dt is the fixed step, 1/60 by default.

```aes
func FixedUpdate(dt float) {
}
```

## Reloaded

Reloaded runs after a hot reload for every instance whose script or a dependency changed. Ready does not run again.

```aes
func Reloaded() {
}
```

## node

node is the NodeRef of the node this instance is attached to. It exists in every script method.

```aes
t := node.Transform2D()
```

## bool

bool is true or false. Conditions of if and for must be bool.

## int

int is a signed 64-bit integer that wraps on overflow. Convert with float(i) and int(f); there is no implicit conversion.

## float

float is a 32-bit IEEE number. float → int conversion saturates and maps NaN to 0.

## string

string is immutable UTF-8 text. + concatenates, len counts bytes, string(x) converts bool, int and float.

## Vec2

Vec2 is a 2D vector with lanes X and Y. Build it with a composite literal; it supports +, -, and * or / by a float.

```aes
v := Vec2{1, 0} * Speed
```

## Vec3

Vec3 is a 3D vector with lanes X, Y and Z.

```aes
up := Vec3{0, 1, 0}
```

## Color

Color has lanes R, G, B and A in linear space, from 0 to 1.

```aes
red := Color{1, 0, 0, 1}
```

## Quat

Quat is a 3D rotation with lanes X, Y, Z and W. Build it with math.QuatEuler or math.QuatAxisAngle. Quats cannot be compared with ==.

## Rect

Rect has lanes X, Y, W and H.

## Transform2D

Transform2D holds Position Vec2, Rotation float in radians (clockwise) and Scale Vec2. It is a value: read it, change it, write it back.

```aes
t := node.Transform2D()
t.Position.X += 1
node.SetTransform2D(t)
```

## Transform3D

Transform3D holds Position Vec3, Rotation Quat and Scale Vec3.

```aes
t := node.Transform3D()
t.Position.Y += 1
node.SetTransform3D(t)
```

## NodeRef

NodeRef references a scene node and may be nil. Exported NodeRef fields are set by dragging a node onto the field in the Inspector.

```aes
@export var Target NodeRef
```

## AssetRef

AssetRef<Texture | Scene | Prefab | Mesh> references an asset and may be nil. Assign it in the Inspector.

```aes
@export var Bullet AssetRef<Prefab>
```

## ComponentRef

ComponentRef<T> references a component on a node and is re-validated on every access.

```aes
sr := node.Get<SpriteRenderer>()
if sr != nil {
	sr.FlipX = true
}
```

## len

len returns the number of elements of a slice or the number of bytes of a string.

```aes
n := len(items)
```

## append

append returns the slice with v added at the end. Assign the result back.

```aes
hits = append(hits, 5)
```

## coroutine

coroutine after a method signature makes the method a coroutine: it can pause with yield and continue on a later frame. Only script methods without a result can be coroutines, and lifecycle methods cannot. Run one with start Name(args).

```aes
func Blink() coroutine {
	yield wait(0.1)
}
```

## start

start runs a coroutine method of this script up to its first yield and returns its Coroutine handle. The coroutine belongs to the instance and is cancelled when the instance stops.

```aes
blink = start Blink()
```

## yield

yield pauses the current coroutine:
```text
  yield            next frame
  yield wait(s)    after s seconds of game time
  yield frames(n)  after n frames
  yield fixed(n)   after n fixed steps
  yield c          when coroutine c ends
```
yield is allowed only inside a coroutine (AES2050).

## yield wait

yield wait(seconds float) resumes after the given game time has passed, at the earliest on the next frame.

```aes
yield wait(0.25)
```

## yield frames

yield frames(n int) resumes after n frames; frames(1) is the same as a bare yield.

```aes
yield frames(3)
```

## yield fixed

yield fixed(n int) resumes after n fixed steps, before physics; use it for movement that must stay in step with FixedUpdate.

```aes
yield fixed(1)
```

## signal

signal declares an event of the script. Only the script itself can Emit it; other scripts Connect to it through a ScriptRef.

```aes
signal Died(reason string)
```

## Emit

Emit calls every connected handler synchronously, in connection order. Connections added or removed by a handler apply after this Emit returns.

```aes
Died.Emit("fall")
```

## Connect

Connect registers a method with the same parameters as the signal and returns a Connection. The handler must be a plain method: not a coroutine and not a lifecycle method.

```aes
conn = enemy.Died.Connect(OnEnemyDied)
```

## Disconnect

Disconnect removes the handler; calling it twice is harmless.

```aes
conn.Disconnect()
```

## Connected

Connected reports whether the connection is still active. It becomes false after Disconnect or when the source or the handler owner stops.

## Stop

Stop cancels the coroutine; it does not run again. Stopping a finished coroutine is harmless.

```aes
blink.Stop()
```

## Running

Running reports whether the coroutine is still alive (not finished, cancelled or faulted).

```aes
if !blink.Running() {
	blink = start Blink()
}
```

## Coroutine

Coroutine is a handle returned by start. The zero value is nil and is never running.

## Connection

Connection is a handle returned by Connect. Keep it in a field to Disconnect later.

## ScriptRef

ScriptRef<T> references a script instance on a node. Through it you read and write fields, call plain methods and connect to signals of T. Lifecycle methods and coroutines are not reachable (AES2059). It becomes invalid when the instance stops; access then faults with AES6004.

```aes
var enemy ScriptRef<EnemyAI>
```

## GetScript

GetScript<T>() returns the instance of script T on the node, or nil when the node has none. Use pkg.Name when the short name is ambiguous.

```aes
e := Target.GetScript<EnemyAI>()
if e != nil {
	e.Died.Connect(OnEnemyDied)
}
```

## Copy

Returns a copy of a data asset as a struct the script owns. Changing the copy does not change the asset.

```aes
s := Stats.Copy()
```

## Row

Returns the row of a table with the given id. A missing row stops the script with AES6004; check with Has first.

```aes
entry := Loot.Row("goblin")
```

## Has

Reports whether a table has a row with the given id.

## Len

Returns the number of rows in a table.
