# Values

Values are the fundamental data types in Storybook. Every field in a character, template, or other declaration contains a value. This chapter provides a complete reference for all supported value types.

## Value Types Overview

Storybook supports 12 value types:

| Type | Example | Use Case |
|------|---------|----------|
| **Number** | `42`, `-7` | Quantities, IDs, counts |
| **Decimal** | `3.14`, `-0.5` | Measurements, probabilities |
| **Text** | `"Hello"`, `"Martha"` | Text, names, descriptions |
| **Boolean** | `true`, `false` | Flags, switches |
| **Time** | `14:30`, `09:15:30` | Clock times, schedule blocks |
| **Duration** | `2h30m`, `45s` | Time intervals |
| **Range** | `20..40`, `0.5..1.0` | Template variation bounds |
| **Identifier** | `Martha`, `items::sword` | References to other declarations |
| **List** | `[1, 2, 3]`, `["a", "b"]` | Collections |
| **Object** | `{x: 10, y: 20}` | Structured data |
| **ProseBlock** | `---tag content ---` | Long-form narrative |
| **Override** | `TemplateX with {...}` | Template instantiation with modifications |

## Integer

Signed 64-bit integers.

### Syntax
```bnf
<int> ::= ["-"] <digit>+
<digit> ::= "0".."9"
```

### Examples
```storybook
character Hero {
    age: 25
    gold: 1500
    reputation: -10
}
```

### Range
- Minimum: `-9,223,372,036,854,775,808`
- Maximum: `9,223,372,036,854,775,807`

### Use Cases
- Counts (items, population)
- Identifiers (IDs, keys)
- Scores (reputation, alignment)
- Whole quantities (gold pieces, HP)

## Float

64-bit floating-point numbers (IEEE 754 double precision).

### Syntax
```bnf
<float> ::= ["-"] <digit>+ "." <digit>+
          | ["-"] <digit>+ ("e" | "E") ["+"|"-"] <digit>+
```

### Examples
```storybook
character Wizard {
    mana: 100.0
    spell_power: 1.5
    corruption: 0.03
    precision: 1e-6
}
```

### Special Values
- No `NaN` or `Infinity` support (use validation to prevent)
- Negative zero (`-0.0`) equals positive zero (`0.0`)

### Use Cases
- Probabilities (0.0 to 1.0)
- Percentages (0.0 to 100.0)
- Measurements with precision
- Ratios and scaling factors

## String

UTF-8 encoded text enclosed in double quotes.

### Syntax
```bnf
<string> ::= '"' <string-char>* '"'
<string-char> ::= <any-char-except-quote-or-backslash>
                | <escape-sequence>
<escape-sequence> ::= "\n" | "\r" | "\t" | "\\" | "\""
```

### Escape Sequences
- `\n` - Newline
- `\r` - Carriage return
- `\t` - Tab
- `\\` - Backslash
- `\"` - Double quote

### Examples
```storybook
character Martha {
    name: "Martha Baker"
    greeting: "Fresh from the oven!"
    multiline: "Line 1\nLine 2\nLine 3"
    quote: "She said, \"The bread is ready!\""
}
```

### Limitations
- No raw strings (r"...") or multi-line literals
- For long text, use [prose blocks](#prose-blocks)
- Maximum length: Implementation-defined (typically several MB)

### Use Cases
- Character names
- Short descriptions
- Dialogue snippets
- Enum-like values (before proper enums)

## Boolean

Logical true/false values.

### Syntax
```bnf
<bool> ::= "true" | "false"
```

### Examples
```storybook
character Guard {
    is_awake: true
    has_seen_player: false
    loyal_to_king: true
}
```

### Use Cases
- Feature flags (can_fly, is_hostile)
- State tracking (door_open, quest_complete)
- Conditions (is_friendly, accepts_bribes)

## Time

Clock time in 24-hour format.

### Syntax
```bnf
<time> ::= <hour> ":" <minute>
         | <hour> ":" <minute> ":" <second>

<hour> ::= "0".."23"
<minute> ::= "0".."59"
<second> ::= "0".."59"
```

### Examples
```storybook
schedule BakerySchedule {
    block {
        start: 06:00
        end: 08:30
        action: baking::prepare_dough
    }

    block {
        start: 14:30:15  // With seconds
        end: 15:00:00
        action: baking::afternoon_cleanup
    }
}

character EarlyRiser {
    wake_time: 05:30
    bedtime: 21:00
}
```

### Validation
- Hours: 0-23 (24-hour format)
- Minutes: 0-59
- Seconds: 0-59 (optional)
- No AM/PM notation
- No timezone support (context-dependent)

### Use Cases
- Schedule blocks (see [Schedules](./16-schedules.md))
- Character routines
- Event timing
- Time-based conditions

## Duration

Time intervals with hour/minute/second components.

### Syntax
```bnf
<duration> ::= <duration-component>+

<duration-component> ::= <number> ("h" | "m" | "s")

<number> ::= <digit>+
```

### Examples
```storybook
character Traveler {
    journey_time: 2h30m
    rest_needed: 8h
    sprint_duration: 45s
}

behavior TimedAction {
    choose {
        timeout(5m) {
            CompleteObjective
        }

        cooldown(30s) {
            UseSpecialAbility
        }
    }
}
```

### Components
- `h` - Hours
- `m` - Minutes
- `s` - Seconds

Can combine multiple components: `1h30m15s`

### Validation
- All components non-negative
- No fractional components (`1.5h` not allowed; use `1h30m`)
- Can specify same unit multiple times: `90m` = `1h30m` (normalized)

### Use Cases
- Behavior tree timeouts/cooldowns
- Travel times
- Cooldown periods
- Event durations

## Range

Numeric range with inclusive bounds (for templates only).

### Syntax
```bnf
<range> ::= <value> ".." <value>
```

Both bounds must be the same type (both int or both float).

### Examples
```storybook
template Villager {
    age: 18..65
    wealth: 10..100
    height: 150.0..190.0  // Float range
}

template RandomEvent {
    probability: 0.0..1.0
    damage: 5..20
}
```

### Semantics
- **Templates only**: Ranges are only valid in templates
- **Instantiation**: When a template is used, a specific value within the range is selected
- **Inclusive bounds**: Both `min` and `max` are included
- **Order matters**: `min` must be ≤ `max`

### Validation
- Both bounds same type
- `min` ≤ `max`
- Cannot use ranges in character/species/etc. (only templates)

### Use Cases
- Template variation
- Procedural generation
- Random NPC attributes
- Loot table ranges

## Identifier

Reference to another declaration by qualified path.

### Syntax
```bnf
<identifier> ::= <simple-name>
               | <qualified-path>

<simple-name> ::= <ident>

<qualified-path> ::= <ident> ("::" <ident>)+
```

### Examples
```storybook
character Martha: Human {  // Species reference
    // ...
}

character Elena from Apprentice {  // Template reference
    // ...
}

character Guard {
    uses behaviors: [
        { tree: guards::patrol }  // Behavior reference
    ]
    uses schedule: DailyRoutine  // Schedule reference
}

relationship Partnership {
    Martha  // Character reference
    Jane  // Character reference
}
```

### Resolution
- **Unqualified**: Searches current module, then imports
- **Qualified**: `module::submodule::Name`
- **Validation**: Compiler ensures all references resolve

### Use Cases
- Species typing (`: Species`)
- Template inheritance (`from Template`)
- Behavior tree references
- Schedule references
- Relationship participants
- Cross-references

## List

Ordered collection of values.

### Syntax
```bnf
<list> ::= "[" "]"
         | "[" <value> ("," <value>)* "]"
```

### Examples
```storybook
character Mage {
    known_spells: ["Fireball", "Lightning", "Shield"]
    spell_levels: [3, 5, 2]
    party_members: [Martha, Jane, Elena]
}

character Traveler {
    inventory: [
        {item: "Sword", damage: 10},
        {item: "Potion", healing: 50},
        {item: "Key", opens: "TowerDoor"}
    ]
}
```

### Type Constraints
- **Homogeneous preferred**: All elements should be the same type
- **Heterogeneous allowed**: Mixed types permitted but discouraged
- **Empty lists**: `[]` is valid

### Operations
Lists are immutable at declaration time. Runtime list operations depend on the execution environment.

### Use Cases
- Collections (inventory, spells, party members)
- References (multiple behaviors, schedules, participants)
- Enum-like sets (before proper enums)

## Object

Structured data with named fields.

### Syntax
```bnf
<object> ::= "{" "}"
           | "{" <field> ("," <field>)* "}"

<field> ::= <identifier> ":" <value>
```

### Examples
```storybook
character Hero {
    position: {x: 100, y: 200}

    stats: {
        strength: 15,
        dexterity: 12,
        intelligence: 10
    }

    equipment: {
        weapon: {
            name: "Longsword",
            damage: 10,
            enchantment: "Fire"
        },
        armor: {
            name: "Plate Mail",
            defense: 8
        }
    }
}
```

### Nesting
Objects can be nested arbitrarily deep:
```storybook
character Complex {
    deep: {
        level1: {
            level2: {
                level3: {
                    value: 42
                }
            }
        }
    }
}
```

### Use Cases
- Structured data (position, stats)
- Nested configurations
- Inline data structures
- Complex field values

## Prose Blocks

Long-form narrative text with semantic tags.

### Syntax
```bnf
<prose-block> ::= "---" <tag> <content> "---"

<tag> ::= <identifier>

<content> ::= <any-text-except-triple-dash>
```

### Common Tags
- `---description`: General description
- `---backstory`: Character history
- `---appearance`: Physical description
- `---personality`: Behavioral traits
- `---motivation`: Goals and desires
- `---notes`: Meta-commentary
- `---ecology`: Species habitat/behavior
- `---culture`: Social structures
- `---narrative`: Story context

### Examples
```storybook
character Martha {
    age: 34

    ---backstory
    Martha learned to bake from her grandmother, starting at age
    twelve. She now runs the most popular bakery in town, known
    for her sourdough bread and unwavering quality standards.
    ---

    ---personality
    Meticulous and patient, with an unwavering commitment to
    quality. Tough but fair with her staff, and deeply loyal
    to the customers who have supported her bakery for years.
    ---
}

species Dragon {
    lifespan: 1000

    ---ecology
    Dragons nest in high mountain caves and emerge every few decades
    to hunt large prey. They hoard treasure as a mating display.
    ---
}
```

### Formatting
- Leading/trailing whitespace is preserved
- No escape sequences needed
- Can contain any characters except `---` on its own line
- Indentation is significant for readability but not semantics

### Multiple Prose Blocks
A single declaration can have multiple prose blocks with different tags:
```storybook
character Gandalf {
    ---appearance
    An old man with a long gray beard, pointed hat, and staff.
    ---

    ---backstory
    One of the Istari sent to Middle-earth to contest Sauron.
    ---

    ---personality
    Patient and wise, but with a mischievous streak.
    ---
}
```

### Use Cases
- Character backstories
- Species descriptions
- World-building flavor text
- Design notes
- Narrative context

## Override

Template instantiation with field modifications.

### Syntax
```bnf
<override> ::= <qualified-path> "with" "{" <override-op>* "}"

<override-op> ::= <identifier> ":" <value>           // Set
                | "remove" <identifier>              // Remove
                | "append" <identifier> ":" <value>  // Append (for lists)
```

### Examples

#### Basic Override
```storybook
template BaseWarrior {
    strength: 10
    dexterity: 8
    weapon: "Sword"
}

character StrongWarrior {
    stats: BaseWarrior with {
        strength: 15  // Override strength
    }
}
```

#### Remove Fields
```storybook
template FullEquipment {
    helmet: "Iron"
    chest: "Plate"
    legs: "Mail"
    boots: "Leather"
}

character LightFighter {
    equipment: FullEquipment with {
        remove helmet
        remove chest
    }
}
```

#### Append to Lists
```storybook
template BasicSpells {
    spells: ["Fireball", "Shield"]
}

character AdvancedMage {
    magic: BasicSpells with {
        append spells: "Teleport"
        append spells: "Lightning"
    }
    // Result: ["Fireball", "Shield", "Teleport", "Lightning"]
}
```

#### Complex Override
```storybook
template RogueTemplate {
    stealth: 15
    lockpicking: 12
    backstab_damage: 20
    equipment: ["Dagger", "Lockpicks"]
}

character MasterThief {
    abilities: RogueTemplate with {
        stealth: 20              // Set
        remove backstab_damage   // Remove
        append equipment: "Grappling Hook"  // Append
    }
}
```

### Operations

#### `set` (default)
Replace a field's value:
```storybook
field_name: new_value
```

#### `remove`
Delete a field from the template:
```storybook
remove field_name
```

#### `append`
Add to a list field (field must be a list):
```storybook
append field_name: value_to_add
```

### Validation
- Base template must exist
- Overridden fields must exist in template
- Removed fields must exist in template
- Appended fields must be lists
- Type compatibility enforced

### Use Cases
- Customizing template instances
- Procedural character generation
- Variant creation
- Data composition

## Type Coercion

Storybook has **no implicit type coercion**. All type conversions must be explicit.

**Not allowed:**
```storybook
character Wrong {
    count: "42"  // Error: expected number, got text
    flag: 1      // Error: expected boolean, got number
}
```

**Correct:**
```storybook
character Right {
    count: 42
    flag: true
}
```

## Null and Optional

Storybook **does not have `null`**. For optional values, use:

1. **Template ranges** with 0 as lower bound:
   ```storybook
   template MaybeWeapon {
       weapon_count: 0..5
   }
   ```

2. **Boolean flags**:
   ```storybook
   character Guard {
       has_weapon: false
   }
   ```

3. **Empty lists**:
   ```storybook
   character Unarmed {
       weapons: []
   }
   ```

## Summary Table

| Type | Mutable? | Comparable? | Valid in Templates? | Notes |
|------|----------|-------------|---------------------|-------|
| Number | No | Yes | Yes | 64-bit signed |
| Decimal | No | Yes | Yes | 64-bit IEEE 754 |
| Text | No | Yes | Yes | UTF-8 |
| Boolean | No | Yes | Yes | true/false |
| Time | No | Yes | No | HH:MM or HH:MM:SS |
| Duration | No | Yes | No | Compounds (2h30m) |
| Range | No | No | Yes (only) | Template variation |
| Identifier | No | Yes | Yes | Declaration reference |
| List | No | Yes | Yes | Ordered collection |
| Object | No | Yes | Yes | Named fields |
| ProseBlock | No | No | Yes | Narrative text |
| Override | No | No | Yes | Template modification |

## Cross-References

- [Characters](./10-characters.md) - Using values in character fields
- [Templates](./16-other-declarations.md#templates) - Range values and override syntax
- [Schedules](./14-schedules.md) - Time and duration in schedules
- [Behavior Trees](./11-behavior-trees.md) - Duration in decorators
- [Expressions](./17-expressions.md) - Using values in conditions

## Related Concepts

- **Immutability**: All values are immutable at declaration time
- **Type safety**: Strong static typing with no implicit coercion
- **Structural equivalence**: Objects/lists compared by structure, not identity
- **Prose as data**: Narrative text is first-class data, not comments
