package dialogue
import "github.com/nsgo-dev/game/pkg/dialogue"Overview
Package dialogue runs branching conversations written as Yarn Spinner (.yarn) scripts: ParseYarn reads a Script of titled nodes, and a Runner steps through it line by line and choice by choice, evaluates its variables and conditions, and hands each <<command>> to Options.OnCommand or publishes it as an Event on a flow.Bus.
Nothing in dialogue reads the wall clock, spawns goroutines or keeps package-level state, and a Runner's variables and visit counts save and load as a State, so a conversation replays the same under nsgotest and survives a save game.
Index
- Constants
- Variables
- type Choice
- type Event
- type Line
- type Options
- type Runner
- func NewRunner(script *Script, opts Options) *Runner
- func (r *Runner) Choose(optionIndex int) (Step, error)
- func (r *Runner) Continue() (Step, error)
- func (r *Runner) CurrentNode() string
- func (r *Runner) LoadState(state State)
- func (r *Runner) SavePart() save.Part
- func (r *Runner) SetVar(name string, val any)
- func (r *Runner) Start(node string) (Step, error)
- func (r *Runner) State() State
- func (r *Runner) Var(name string) (any, bool)
- func (r *Runner) Vars() map[string]any
- func (r *Runner) Visited(node string) int
- type Script
- type State
- type Step
- type StepKind
- type StringResolver
- type VarRef
Constants
const DefaultMaxStepsPerContinue = 1024DefaultMaxStepsPerContinue is the default upper bound on internal statements (assignments, branches, jumps, commands) executed in a single Start, Continue, or Choose call before returning ErrStepLimitExceeded.
Variables
var (
// ErrNilScript is returned when starting a Runner with a nil script.
ErrNilScript = errors.New("dialogue: nil script")
// ErrUnknownNode is returned when starting or jumping to a node not present in the script.
ErrUnknownNode = errors.New("dialogue: unknown node")
// ErrInvalidChoice is returned when Choose receives an out-of-range option index.
ErrInvalidChoice = errors.New("dialogue: invalid choice index")
// ErrChoiceUnavailable is returned when Choose selects an option whose <<if>> guard evaluated false.
// ErrNoPendingChoice is returned when Choose is called while no choice menu is active.
ErrNoPendingChoice = errors.New("dialogue: no pending choices")
// ErrChoiceRequired is returned when Continue is called while a choice menu is awaiting Choose.
ErrChoiceRequired = errors.New("dialogue: waiting for Choose")
// ErrStepLimitExceeded is returned when execution exceeds MaxStepsPerContinue without yielding a line, choice, or end.
ErrStepLimitExceeded = errors.New("dialogue: step limit exceeded")
)Types
type Choice struct {
Index int
Text string
LineID string
Available bool
Tags []string
}Choice holds one option presented at a StepChoices step.
type Event struct {
Command string
Args []string
Node string
}Event is published onto a flow.Bus (via flow.Publish) and/or passed to Options.OnCommand whenever a script executes a game command such as <<give_item key 1>> or <<play_sfx chime>>.
type Line struct {
Speaker string
Text string
LineID string
Tags []string
}Line holds a resolved dialogue line produced by a Runner.
type Options struct {
// Vars, if non-nil, is the shared project variable store that this runner reads and writes
// instead of its private map. When Vars is set, <<declare>> and <<set>> of an undeclared
// variable return an error wrapping flow.ErrUndeclaredVar, and assignments enforce declared kinds and ranges.
Vars *flow.Vars
// Bus, if non-nil, receives a Event via flow.Publish for every game command.
Bus *flow.Bus
// OnCommand, if non-nil, is invoked for every game command after Bus delivery.
OnCommand func(Event)
// StringResolver, if non-nil, resolves localized text for dialogue lines and choices.
StringResolver StringResolver
// MaxStepsPerContinue caps internal statements per Start, Continue, or Choose call
// to guard against infinite <<jump>> loops. Defaults to DefaultMaxStepsPerContinue.
MaxStepsPerContinue int
}Options configures a Runner.
type Runner struct {
// contains filtered or unexported fields
}Runner executes a parsed Script step by step.
It maintains variables, node visit counts, and the active execution stack without goroutines or global state. Game commands execute synchronously and publish typed Event values on Options.Bus when configured.
func NewRunner(script *Script, opts Options) *RunnerNewRunner creates a runner for script with the given options.
func (r *Runner) Choose(optionIndex int) (Step, error)Choose selects optionIndex from the active StepChoices step and advances to the next line, choice menu, or end of dialogue.
func (r *Runner) Continue() (Step, error)Continue advances an active dialogue to the next line, choice menu, or end. Calling Continue while a choice menu is awaiting Choose returns ErrChoiceRequired.
func (r *Runner) CurrentNode() stringCurrentNode returns the title of the currently executing node, or "" when ended.
func (r *Runner) LoadState(state State)LoadState restores variables and visit counts from a previously saved State.
func (r *Runner) SavePart() save.PartSavePart returns a save.Part (implementing save.StagedPart and save.Resetter) that saves and restores r's variables and node visit counts through save.Game. Loading stages the maps before mutating r, and clears variables and visit counts when loading an older save slot that omits it.
func (r *Runner) SetVar(name string, val any)SetVar sets a dialogue variable. A leading '$' is optional and normalized away. When Options.Vars is configured, SetVar writes through to that shared store; otherwise numeric Go types are normalized to float64 in the runner's private map.
func (r *Runner) Start(node string) (Step, error)Start begins executing the script at the named node and advances until the first line, choice menu, or end of dialogue.
func (r *Runner) State() StateState returns a serializable snapshot of the runner's variables and visit counts.
func (r *Runner) Var(name string) (any, bool)Var returns the current value of name (leading '$' optional) and whether it is set. When Options.Vars is configured, Var reads from that shared store.
func (r *Runner) Vars() map[string]anyVars returns a shallow copy of all currently set dialogue variables (keys without leading '$'). When Options.Vars is configured, Vars returns a snapshot of that shared store.
func (r *Runner) Visited(node string) intVisited returns how many times the named node has been entered via Start or <<jump>>.
type Script struct {
// contains filtered or unexported fields
}Script is a parsed Yarn Spinner script containing one or more named nodes. A parsed Script is immutable and safe to share across multiple Runners.
func ParseYarn(src string) (*Script, error)ParseYarn parses Yarn Spinner (.yarn) source text into a reusable Script.
Supported syntax:
- Node headers (title: ..., custom key: value) delimited by --- and ===
- Comments starting with //
- Dialogue lines: [Speaker: ]Text [#line:id] [#tag ...] with {expr} interpolation
- Branching choices: -> Option text [<<if cond>>] [#line:id] [#tag ...] with indented bodies
- Conditionals: <<if expr>> / <<elseif expr>> / <<else>> / <<endif>>
- Variables: <<set $var = expr>> (plus to, +=, -=, *=, /=) and <<declare $var = expr>>
- Control flow: <<jump NodeTitle>> and <<stop>>
- Game commands: <<command arg1 "quoted arg" $var {$expr}>>
Its errors are *loaderr.Error values that give the line of the problem and how to fix it; a caller that read src from a file names it with loaderr.WithFile.
func (s *Script) HasNode(title string) boolHasNode reports whether the script contains a node with the given title.
func (s *Script) NodeHeaders(title string) map[string]stringNodeHeaders returns a copy of the header metadata declared on the named node, or nil if the node does not exist.
func (s *Script) Nodes() []stringNodes returns the script's node titles in declaration order.
func (s *Script) VarRefs() []VarRefVarRefs returns all variable references in s in source order (by node declaration order and statement order), including <<set>>, <<declare>>, <<if>>/<<elseif>>, choice guards, {expr} interpolations, and $var command arguments.
type State struct {
Vars map[string]any `json:"vars,omitempty"`
Visited map[string]int `json:"visited,omitempty"`
}State is a JSON-serializable snapshot of a Runner's variables and node visit counts for save/load persistence.
type Step struct {
Kind StepKind
Line Line
Choices []Choice
}Step is the result of Start, Continue, or Choose on a Runner.
type StepKind intStepKind identifies what a Step produced.
const (
// StepEnded indicates the dialogue reached the end of a node, hit <<stop>>, or has not started.
StepEnded StepKind = iota
// StepLine indicates a single spoken or narrated line is ready to display.
StepLine
// StepChoices indicates one or more player choices are awaiting Choose.
StepChoices
)func (k StepKind) String() stringString returns a human-readable name for the StepKind.
type StringResolver func(lineID, fallback string, vars map[string]any) stringStringResolver resolves localized text for a dialogue line or choice.
It receives the #line:<id> identifier (empty if untagged), the raw source text from the Yarn script as fallback, and a snapshot of the runner's variables. Any remaining {expr} placeholders in the returned string are interpolated by the runner using its current variables.
type VarRef struct {
// Name is the variable name without any leading '$'.
Name string
// Line is the 1-based line number in the Yarn source where the reference appears.
Line int
// Node is the title of the dialogue node containing the reference.
Node string
// Write reports whether the reference assigns to the variable (<<set>> or <<declare>>).
Write bool
// Declare reports whether the reference is a <<declare>> statement.
Declare bool
}VarRef describes one variable reference found in a parsed Script, used by static checks (such as game check) to verify variable names against vars.yaml.