GitHubНачать

Эта страница ещё не переведена на русский язык, поэтому ниже показан английский оригинал.

Системы 2D

datatable

game/datatable loads typed game data, such as enemies, items, levels and quests, into slices of your own Go struct, and reloads it while the game runs when a designer saves the file. Tables are YAML, so designers and AI tools edit them directly and every change reads as a line in review; CSV and JSON exports from spreadsheets and other tools load too.

import "github.com/nsgo-dev/game/pkg/datatable"

A table and its type

A row type is a struct. Each field is a column named by its table tag, else its json tag, else its Go field name; a tag of - leaves the field out. Fields can be strings, bools, integers, unsigned integers, floats, time.Duration, pointers to these (absent or null leaves the pointer nil) and slices of them.

type Enemy struct {
	ID       string        `table:"id,key"`
	Name     string        `table:"name"`
	HP       int           `table:"hp"`
	Speed    float64       `table:"speed"`
	Boss     bool          `table:"boss"`
	Tags     []string      `table:"tags"`
	Cooldown time.Duration `table:"cooldown"`
}

The YAML file is a mapping with a version, which is datatable.FormatVersion (1), and a rows list. Each row is a mapping from column names to values; a column a row leaves out keeps its zero value.

version: 1
rows:
  - id: goblin
    name: Cave Goblin
    hp: 45
    speed: 3.5
    boss: false
    tags: [melee, scout]
    cooldown: 500ms
  - id: dragon
    name: Ancient Wyrm
    hp: 1200
    speed: 6.25
    boss: true
    tags: [flying, fire, boss]
    cooldown: 2s

LoadFile[T](path) picks the reader by extension (.yaml, .yml, .csv or .json); LoadYAML[T](name, data) reads bytes you already have, such as an embedded file.

enemies, err := datatable.LoadFile[Enemy]("data/enemies.yaml")

Add ,key to designate one string or integer column as the primary key. YAML, CSV, and JSON readers report duplicate keys with the offending cell and the first row that used the key. Unknown options in a table tag are an error.

A loaded Table[Enemy] can find an enemy with table.Get("goblin"). The argument uses the key field's exact Go type. For several reads from the same generation, use table.View().Get("goblin").

What a YAML table refuses

A YAML table is strict, so a typo is an error at load time rather than a silently missing value:

  • a missing version, a version other than 1, or a top-level key other than version and rows;
  • a bare list of rows without the version/rows mapping, or a second YAML document after ---;
  • a row key that names no column (datatable.ErrUnknownField), including a field tagged -;
  • a column set twice in one row, for example as hp and HP (datatable.ErrDuplicateField);
  • a merge key (<<: *defaults): anchors and aliases load, but each row spells out its own columns;
  • a value the field's type cannot hold, such as speed: fast or an int8 of 300.

Errors inside a row are a *datatable.CellError with the file, the 1-based row, the column and the value:

var ce *datatable.CellError
if errors.As(err, &ce) {
	log.Printf("%s row %d, %s = %q: %v", ce.File, ce.Row, ce.Field, ce.Value, ce.Err)
}

Column names match exactly first and then without regard to case, so Armor and armor both fill a field named Armor. CSV and JSON stay as their tools export them: they have no version, and columns the type does not have are skipped.

Saving a table

MarshalYAML(rows) and SaveYAML(path, rows) write the same format, for an editor or a script that generates data. The output is deterministic: version first, then every column of every row in struct declaration order, two-space indentation, lists inline, strings quoted only where YAML needs it, a nil pointer as null and a duration in its String form. A file saved by SaveYAML, loaded and saved again is byte for byte the same. A nil list and an empty list are both written as []. Non-finite floats and field types the loader cannot read (maps, structs, interfaces) are an error.

Every column has one field: a row type in which two fields share a column name, such as two fields tagged hp or an embedded struct's name and the outer struct's own name, is refused by both LoadYAML and MarshalYAML, because only one of the two could be written or read back. Give each field its own tag, or tag one of them -.

if err := datatable.SaveYAML("data/enemies.yaml", enemies); err != nil {
	return err
}

Untyped editing and row-type validation

Tools and editors that work on YAML data tables without importing every game's Go row struct can open a file as an untyped *datatable.Document with ParseDocument or LoadDocument:

  • Each Row stores an ordered slice of Cell{Key, Value} entries so per-row key order is preserved, Columns() returns the union of row keys in first-appearance order, and ColumnKind(col) infers KindString, KindNumber, KindBool, KindDuration, or KindList.
  • Marshal and Save return the exact input bytes when no edits were made, patch only the edited line when a single scalar or inline-list cell changes, and encode deterministically from the preserved YAML AST after structural edits (AddRow, DeleteRow, MoveRow).
  • RowTypeFor[T]() and Registry (RegisterRowType[T](reg, pattern)) validate untyped cells, rows, and documents against Go struct types with LoadYAML's exact rules (ValidateCell, ValidateRow, ValidateDocument, ParseCellText), refusing unknown fields, duplicate fields, and type-conversion failures with *datatable.CellError.

The registry can also check files directly. reg.CheckFS(os.DirFS(projectDir)) reads the .yaml and .yml files matched by the registered patterns and returns the first problem per file, in filesystem walk order. Each problem carries the file path relative to the supplied directory, the 1-based line and column when known, and a message. Pass the registry to the project editor command through editorcmd.Options.DataTables to run the same checks with game check.

Hot reload

NewTable[T](path) loads the file and holds its rows. datatablewatch.Watch (in game/datatable/datatablewatch) registers it with a hotreload.Watcher (from game/tooling/hotreload) and calls back on the engine goroutine with the new rows after each valid save. datatable itself imports no NSGo package, so a dedicated server loads tables with it headlessly; only the game client links the watcher:

func Game(cx *core.Scope) core.Node {
	enemies, err := datatable.NewTable[Enemy]("data/enemies.yaml")
	if err != nil {
		panic(err)
	}
	w := hotreload.NewWatcher(cx, "data")
	datatablewatch.WatchWithError(enemies, w, func(rows []Enemy, err error) {
		if err != nil {
			log.Printf("enemies.yaml: %v", err) // rows are still the last valid ones
			return
		}
		spawner.SetEnemies(rows)
	})
	// ...
}

An edit that does not load, such as a misspelt column, keeps the previous rows, leaves Version unchanged and records the error in LastError; the next valid save replaces the rows and increases Version. Rows returns a copy, so callers cannot change the table's rows. In release builds (-tags release) the watcher is a no-op and the table keeps the rows it loaded at start.

Immutable views

Table.View returns a View holding the table's current rows and the Version they were loaded as, read together under one lock, so the two always come from the same load. View.Rows returns the table's own slice without copying it, so a caller reading rows every tick allocates nothing; the slice and its rows are read-only, and changing them changes what every other holder of the view sees. A reload publishes a new slice and leaves an existing View unchanged, so a server pins a View when a match starts, records its Version with the match or replay, and new matches pick up the reloaded rows. Rows still returns a copy.

Reloading a set of tables

Register each file and row type with datatable.RegisterTable[T](set, name, path), then call set.Reload() to load them together. If a file cannot load or the validation function supplied to NewSet rejects the candidate, Current() keeps the previous snapshot. Use the validator to check relationships between tables before they become visible.

Current() returns the latest snapshot or nil before the first successful load. Keep that snapshot for the duration of a match. Read its shared rows with datatable.Rows[T](snapshot, name) or find one row with datatable.Lookup[T](snapshot, name, key). Treat the rows and nested values as read-only. A later reload advances snapshot.Version() on the new publication and leaves existing snapshots intact. Server matches.

Declare a cross-table reference with table:"boss,ref=monsters". Register the target under that name and mark one of its columns with ,key. The source field may contain a scalar or a slice whose element type matches the target key's Go type. Set reloading checks every reference before publication. A missing key reports its file, row and column name and leaves the previous snapshot available.

Редактировать страницу