Smart Variables

Smart variables in Yarn Spinner are variables whose value comes from an expression. A smart variable’s value is worked out from its expression each time it’s read.

Why Use Smart Variables?

A smart variable gives a long condition a name. You write the condition once, in the declaration, and use the name everywhere else.

Examples

To create a smart variable, use the <<declare>> command followed by a variable name (with the $ prefix) and assign it an expression rather than a static value. The expression can use mathematical operations, logical comparisons, or reference other variables.

For example: <<declare $is_powerful = $strength > 50 && $magic_ability >= 20>>.

Your dialogue responds to changes in $strength or $magic_ability without additional code.

Example 1: Character Relationships

Yarn
title: Start
---
<<declare $player_is_friends_with_sam = $sam_relationship_score > 50>>

<<if $player_is_friends_with_sam>>
  Sam: I saved you the last apple pie.
<<else>>
  Sam: Pies are four gold each. No discounts.
<<endif>>
===
A smart variable for a character relationship.

Example 2: Item Availability

Yarn
title: Start
---
<<declare $has_enough_materials = $wood >= 5 && $nails >= 10>>
<<declare $has_required_skill = $carpentry_level >= 3>>
<<declare $can_build_chair = $has_enough_materials && $has_required_skill>>

<<if $can_build_chair>>
  Craftsman: Five planks and ten nails. That's enough for a chair.
<<else>>
  <<if !$has_enough_materials>>
    Craftsman: A chair takes five planks and ten nails. Come back when you have them.
  <<else>>
    Craftsman: You have the wood and the nails, but you need more practice before you try a chair.
  <<endif>>
<<endif>>
===
Smart variables for item availability.
flowchart BT
  chair_wood["$wood"]
  chair_nails["$nails"]
  chair_level["$carpentry_level"]
  chair_materials(["$has_enough_materials<br>$wood #gt;= 5 #amp;#amp; $nails #gt;= 10"])
  chair_skill(["$has_required_skill<br>$carpentry_level #gt;= 3"])
  chair_build(["$can_build_chair<br>$has_enough_materials #amp;#amp; $has_required_skill"])
  chair_wood --- chair_materials
  chair_nails --- chair_materials
  chair_level --- chair_skill
  chair_materials --- chair_build
  chair_skill --- chair_build
The variables in the chair example. The rounded boxes are smart variables, each worked out from the variables below it.

Example 3: Time-Based Events

Yarn
title: Start
---
<<declare $is_evening = $game_hour >= 18 && $game_hour < 22>>
<<declare $town_shops_open = !$is_holiday && $game_hour >= 9 && $game_hour < 18>>

<<if $is_evening && !$town_shops_open>>
  Innkeeper: The bakery shut at six. I can do you bread and cheese.
<<endif>>
===
Smart variables for time-based events.

Benefits in Complex Games

Smart variables help most when you have conditions that you check frequently or that combine multiple factors.