Bruja language reference
Bruja mixes Ink-style story writing (dialogue, choices, threads) with a small Lua/Python-style scripting language. Blocks are defined by indentation, like Python.
Every example here has a matching test in tests/Bruja.Tests/Scripts/.
Story
Dialogue
> You enter a dark room.
> The air smells of smoke, {name}.
A line starting with > is shown to the player. In a game, each Continue() returns
one line. A line whose text comes out empty (> [if: hungry | I'm starving. | ] with hungry
false, or a line of nothing but markup) is skipped, tags and all, instead of showing a blank line.
Speakers
> @Mira: I'm fine.
> @Mira (sad): I'm not fine.
@Name: at the start of a dialogue line (or a question) says who is talking. It isn’t shown;
the game gets it as a tag: the lines above have the tags ["speaker:Mira"] and
["speaker:Mira", "portrait:sad"]. The name and the portrait are single words (letters,
digits and _). An explicit #speaker: or #portrait: tag on the line wins over the shorthand.
Choices don’t have speakers: * @Mira: hi is shown as written.
\@ writes a literal @. A line that starts with @name but has no : after it is shown as
written, with a warning. A speaker used only once whose name is close to another speaker’s
(@Mria in a story full of @Mira) is also a warning.
Text features
Inside dialogue, questions and choices:
| Write | Shows |
|---|---|
{expr} |
the value of any expression: {gold * 2}, {items}, {greet(name)} |
[a|b|c] |
the next one each time it’s shown, then sticks on the last (sequence) |
[cycle: a|b] or [@ a|b] |
loops through them |
[one: a|b] or [! a|b] |
picks one at random the first time, then always that one |
[any: a|b], [rand: a|b] or [* a|b] |
random every time |
[rseq: a|b|c] or [~ a|b|c] |
random order, then sticks on the last |
[rcycle: a|b|c] or [$ a|b|c] |
random order, reshuffled each round |
[if: cond | yes | no] or [? cond | yes | no] |
yes when cond is truthy, else no (optional) |
[count: n | zero | one | many] or [# n | ...] |
picks by number; the last one covers anything larger |
[and: a|b|c] / [or: a|b|c] |
“a, b, and c” / “a, b, or c” |
[cycle: names], [and: items] |
with one part, the part is an array expression |
#tag |
tags at the end of a line: not shown, passed to the game (#1 and # stay text) |
<b>, <color=red>, <pause=0.5> |
markup (see Markup) |
\{ \} \[ \] | \# \@ \< \\ |
literal characters |
[text] with no | and no kind is shown as-is, brackets included.
Variations can nest and contain {expressions}:
> [Hi {name}|Hello [again|once more]|Bye]. Expressions can use the enclosing
function’s local variables.
Markup
> It was <b>huge</b>. <i>Really</i> huge.
> <color=red>Danger!</color> <size=150%>RUN</size>
> Wait for it...<pause=0.8> boom. <shake>The floor shakes.</shake>
Tags in angle brackets style the text, like TextMeshPro’s rich text:
| Tag | |
|---|---|
<b>…</b>, <i>…</i>, <u>…</u>, <s>…</s> |
bold, italic, underline, strikethrough |
<color=red>…</color> |
a color name or hex digits: <color=ff8800> (a # is optional) |
<size=120%>…</size> |
bigger or smaller text |
<pause=0.5> |
a pause in seconds, for games that type text out; no closing tag |
<name>…</name>, <name=value>, <name=value/> |
your own tags: passed to the game as they are; /> makes a tag with no closing tag |
- Markup isn’t part of the text:
Continue()andCurrentTextreturnIt was huge. Really huge.. The game gets the markup fromCurrentRichText(for TextMeshPro) orCurrentSpans(the text split into runs, with pauses); see using-stories-in-games. - Tag values can be expressions:
<color={moodColor}>. - Text that comes from variables is never markup:
{name}shows<Bob>as written. - Tags still open at the end of the line end there. A tag that is never closed, a closing tag
without an opening one, and a bad
pause,sizeorcolorvalue are warnings. \<is a literal<. A<that doesn’t start a tag (3 < 5,<3) is text; if it looks like a broken tag (<b oops) you get a warning.- Pauses are only for presentation: the story doesn’t wait. The command line and plain
CurrentTextignore them; the web IDE fades in the text after a pause.
Tags
> Halt! #speaker:guard #vo_101
The game reads them with story.CurrentTags (["speaker:guard", "vo_101"]). Choices can
have tags too (StoryChoice.Tags). > @guard: Halt! #vo_101 is the same line written with the
speaker shorthand (see Speakers).
The tags start at the first # that is followed by a letter or _, and run to the end of the
line; each further # starts another tag. A # followed by anything else is text:
> You're #1! #cheer shows You're #1! with the tag cheer. Write \# for a # that would
otherwise start a tag (\#hashtag).
Line IDs and localization
> @Guard: Halt! Who goes there? #line:g01
> Ah, {name}. You have [count: coins | no coins | a coin | {coins} coins]. #line:g02
* Pay the toll #line:g03
A #line: tag gives a line, question or choice an ID that stays the same when you reword or
move it. A language is a string table of these IDs (the workflow is in localization):
- An entry is a template:
{0},{1}… stand for the line’s{expressions}and variations in order,{{and}}are literal braces, and markup (<b>) is kept:Ah, {0}. Vous avez {1}. - Each alternative of a variation gets its own ID, numbered in the order they are written:
g02.1isno coins,g02.3is{0} coins(where{0}iscoins). - A line missing from the table shows the story’s own text.
- IDs are letters, digits,
-and_, and must be unique (an error names both lines). Once a story uses any IDs, lines without one get a warning.bruja lines addadds them all. - The game reads the current line’s ID as
story.CurrentLineId(also handy for voice-over files).
Questions and choices
> The door is locked.
* {hasKey} Unlock it
> Click.
* Knock #polite
> Nobody answers.
+ Leave
> You leave.
*
> With nothing else to do, you wait.
*is a once-only choice: after it’s picked it is never offered again.+is a sticky choice: always offered.{conditions}at the start of a choice hide it unless all of them are truthy.- A choice with no text is a fallback: never shown; taken automatically when no other choice is available. If there is no fallback either, the story moves past the question.
The question line (> The door is locked.) is shown with the choices. The indented block
under a choice runs when it’s picked; then the story continues after the question.
Threads, jumps and visits
# Chapter One
## Cellar
> It's dark down here.
-> chapter_one.cellar // jump
#,##, … start a thread. Names are lowercased with spaces turned into_; nested threads are addressed with dots.-> namejumps to a thread. A unique last part is enough (-> cellar). Jumping to a thread that doesn’t exist, or to an ambiguous name, is a compile error.->can’t be used inside functions.<- nameruns a thread and comes back: it plays until the next header at the same or a higher level (or the end of its file), then continues after the<-.visits("cellar")is how many times the story has entered that thread.turns()is how many choices the player has made.turnsSince("cellar")is how many turns ago the story last entered a thread: 0 during the turn it was entered, -1 if never. Entering a thread with->,<-or the game’sGoTocounts; a fallback choice taken automatically isn’t a turn.choiceCount()is how many choices the current question has offered so far: use it in a later choice’s condition (* {choiceCount() == 0} Give up) or in the question’s text, which is worked out after its choices.
Files: import
// story.bruja
import "chapters/two.bruja"
import "common.bruja"
> {greet("Ann")}
-> chapter_two
import "file.bruja" makes another file part of the story when it compiles.
- Paths are relative to the file that imports (
import "../common.bruja"works) and use/. - Imports go at the top level of a file, before its first
#thread. - Each file is read once, however many files import it. A file that imports itself, directly or through others, is an error that shows the chain.
- An imported file’s code before its first thread runs where it’s imported (once): it can
define functions, enums and variables, and show lines. Its threads don’t play by
themselves; reach them with
->and<-like any other thread. - All files share one set of names: a thread, top-level function or enum defined twice is an error that names both places. Errors, warnings and runtime errors say which file they are in.
- Compiling needs a way to read the files: compiling from a file does (the command line,
story.CompileFile(path), the Unity importer, the web IDE’s file tabs); otherwise setStoryOptions.Compiler.ResolveImport(see using-stories-in-games).
Pausing for the game
wait "door_opens"
wait 2
wait
wait pauses the story without showing text. In a game, Continue() returns null and
story.CurrentWait holds the value; do what it asks, then call Continue() again.
Asking for text
name = input("What's your name?", "Alex")
while name.trim() == "":
name = input("Please type a name.")
> Hello, {name}.
input(prompt), input(prompt, default) or input(prompt, default, tags) pauses the story until
the player types something, and returns it as a string (check it in the script, as above). It
works anywhere code runs, including functions and generators, but not in event handlers.
Submitting an answer counts as a turn. In a game, Continue() returns null with
story.CurrentInput set (prompt, default, tags); pass the text to story.SubmitInput(text).
A save made while waiting comes back to the same question. A local variable named input hides
the built-in.
Values
| Type | Examples |
|---|---|
| null | null |
| boolean | true, false |
| integer (32-bit) | 42, 0xFF, 0b1010 |
| float (32-bit) | 1.5, .25 |
| string | "text", """multi-line""", @"C:\verbatim" |
| array | [1, 2, 3] |
| object | {name: "Ann", hp: 10}, {"first name": "Ann"} |
| function | func f(): ..., x => x * 2, (a, b) => a + b |
| event | event died |
| generator | what calling a function that contains yield returns (see Generators) |
| dice roll | d20, 3d6 (a random integer each time it’s evaluated) |
| enum member | Mood.sad (see Enums) |
Strings support \n \t \r \0 \\ \" \'. Numbers print the same on every system
(1.5, never 1,5); booleans print true/false.
Truthiness: only null and false are false. 0 and "" are true.
Variables
gold = 10 // global (Lua rules: assigning an unknown name makes a global)
local x = 1 // local to the enclosing function or block
const MAX = 3 // can't be reassigned (checked when the script compiles)
A name is looked up in the current function, then enclosing functions, then globals.
Inside a function, use local for variables that belong to the function.
At the top level of a script, local variables and loop variables belong to the script
itself: functions and closures can use them, but they aren’t globals, so the game can’t
read them with GetVariable. Top-level const values are globals. A top-level function
that uses a top-level local can only be called after its definition has run.
Assignment operators: = += -= *= /= %= **= &= |= ^= <<= >>=, and ++/-- (prefix and
postfix) on variables, a[i] and o.p.
Operators
From highest to lowest precedence:
| Operators | |
|---|---|
f(x) a.b a[i] |
call, member, index |
** |
power (int ** non-negative int stays an int) |
-x ~x |
negate, bitwise not |
* / % |
integer division for two integers; error on division by zero |
+ - |
+ also joins strings ("n=" + 42) |
<< >> |
shifts |
&, ^, | |
bitwise and, xor, or (in that order) |
< > <= >= == != |
1 == 1.0 is true; strings compare by content |
not x !x |
|
and && |
returns the first falsy operand, else the last |
or || |
returns the first truthy operand, else the last: name = name or "stranger" |
and/or stop evaluating as soon as the result is known.
Control flow
if hp <= 0:
> You fall.
else if hp < 10:
> You stagger.
else:
> You stand firm.
while i < 3: // also: until i >= 3: do while cond: do until cond:
i += 1
for i in 1..3: // 1, 2, 3 (1..!3 excludes the end: 1, 2)
for i in 10..0 by 5: // 10, 5, 0 (direction comes from the bounds)
for item in items: // values
for i, item in items: // index, value
for key in obj: // property names
for key, value in obj: // property name, value
switch mood:
case "happy":
> Smile.
case "angry":
> Frown.
default:
> Shrug.
break continue pass return x
until is while with the condition reversed. do while and do until run the block once
before checking the condition.
switch compares with == and never falls through. continue inside a switch continues
the enclosing loop. A one-line block can follow the colon: if done: print("ok").
Functions
func greet(name):
return "Hello, " + name
square = x => x * x
add = (a, b) => a + b
noArgs = () => 42
func makeCounter():
local n = 0
func next():
n += 1
return n
return next // a closure: keeps n alive
- A function without
returnreturnsnull. Calling with the wrong number of arguments is an error. - Functions defined inside functions are local to them and can call themselves.
- Closures capture variables, not values: closures that share a variable see each other’s changes. Each loop iteration gets fresh variables, so closures made in a loop each keep their own (also at the top level of a script).
Generators
A function that contains yield is a generator function. Calling it doesn’t run it: it
returns a generator, which runs the function a piece at a time. Each time a value is asked for,
the function runs until its next yield, hands over that value and pauses there, keeping its
local variables and loops.
func countTo(n):
for i in 1..n:
yield i
for x in countTo(3): // 1, 2, 3
print(x)
for i, x in countTo(2): // i counts from 0: (0, 1), (1, 2)
print(i + " " + x)
g = countTo(2)
g.next() // 1
g.next() // 2
g.next() // null: the function ran off its end
g.done // true
for x in gruns the generator until it finishes (or the loopbreaks).g.next()gets one value, ornullonce the function has finished;g.doneis true after that. A generator that has just yielded its last value isn’t done until it’s asked again, so preferfor.- Generators are lazy: nothing runs until a value is asked for, so they can go on forever
(
while true: yield n). - Each call makes a new, independent generator. Generators can be closures, make closures over their own locals, and read other generators.
return(without a value) stops a generator early;return xin a generator is an error.yieldwith no value yieldsnull.yieldoutside a function is an error (to pause the story for the game, usewait).- While it runs, a generator can show dialogue, ask questions and
wait; the story pauses inside it, and save games keep it, like any function.
func encounters():
> A wolf blocks the path.
* Fight
yield "fought the wolf"
* Sneak past
yield "sneaked past the wolf"
> A troll sits by the bridge.
* Pay the toll
yield "paid the troll"
* Swim
yield "swam the river"
for result in encounters():
> You {result}.
Enums
enum Mood:
happy
sad
angry
enum Weather: sun, rain, fog // the same on one line
mood = Mood.sad
if mood == Mood.sad:
> You look {mood}. // You look sad.
for m in Mood: // happy, sad, angry
print(m)
- The block form ends its first line with
:, likeifandfunc; members go one or more per indented line, separated by commas. - An enum is a set of named values. A member is equal only to itself (
Mood.sad == "sad"is false), prints as its name, and members of one enum are ordered as written (Mood.happy < Mood.angry).switchworks on them. Mood.saddis a compile error that lists the members. Enums are declared at the top level only, can be used above their declaration, and can’t be assigned to.for m in Moodloops over the members;len(Mood)counts them.typeOf(Mood.sad)is"enum"(andtypeOf(Mood)is"enumtype").- Saves store members by name, so adding or reordering members doesn’t break them. Removing a member that a save uses makes loading that save fail with a message.
- In C#:
story.EnumMember("Mood.sad"),value.IsEnum,value.EnumName,value.MemberName.
Events
event died
died += name => print(name + " died")
died += onDeath
died("goblin") // calls every handler, in order
died -= onDeath
Handlers run to completion and can’t show dialogue or ask questions. C# can listen with
story.OnEvent("died", ...) and fire with story.FireEvent("died", ...).
Game functions
Functions the game provides (bound in C# with story.Bind) can be declared so the compiler
knows about them:
extern giveItem, playSound
giveItem("key")
Without the declaration, using them works but produces a “never assigned” warning.
Errors
error("The bridge is out") // stops the story with this message
assert(gold >= 0, "gold went negative") // stops it if the condition is falsy
A script error stops the story with a message that ends in its location, like
Assertion failed: gold went negative at shop.bruja:12:1, and a script call stack. The game
gets it as a StoryRuntimeException from Continue() (and Story.ErrorRaised).
Compiling reports problems as file:line:column: error|warning: message (1-based):
- errors: syntax errors (all of them at once), unknown or ambiguous
->/<-targets,->inside a function, assigning aconst, mistakes inside{...}and[...]in text. - warnings: a name that is read but never assigned (a typo, or a game function missing
extern), a global used by only one function (probably meant to belocal), and speaker mistakes (@Mirawithout a:, or a misspelled speaker used only once), markup that doesn’t match, and lines without a#line:ID in a story that uses them.
bruja check -f story.bruja prints them, and the VS Code extension and the Unity
importer show them in place.
Built-in functions
| Function | |
|---|---|
print(a, b, ...) |
writes its arguments, separated by spaces (console, Unity’s Debug.Log, or the host’s print binding) |
error(message), assert(condition, message) |
stop the story with an error (see Errors) |
toInt(x), toFloat(x), toString(x), toBool(x) |
conversions (toInt("42")) |
typeOf(x) |
"null", "boolean", "integer", "float", "string", "array", "object", "function", "event", "generator", "enum", "enumtype" |
len(x) |
length of a string or array, number of properties of an object, members of an enum |
keys(obj), has(obj, "name") |
property names; whether a property exists |
visits("thread") |
times the story has entered a thread |
input(prompt, default, tags) |
pauses for the player to type; returns the text (see Asking for text) |
turns(), turnsSince("thread") |
choices (and typed answers) so far; turns since a thread was last entered (-1: never) |
choiceCount() |
choices the current question has offered so far |
Arrays: a.length, a.push(x), a.pop(), a.insert(i, x), a.removeAt(i),
a.remove(x), a.contains(x), a.indexOf(x), a.join(), a.join(sep), a.reverse(),
a.clear(), a.copy(), a.slice(start, end).
Strings: s.length, s.toUpper(), s.toLower(), s.substring(start),
s.substring(start, length), s.contains(x), s.startsWith(x), s.endsWith(x),
s.indexOf(x), s.replace(from, to), s.split(sep), s.trim(), s[i].
Math: math.floor, ceil, round(x), round(x, digits) (halves round away from zero), abs, min, max, pow,
sqrt, cbrt, exp, log, log2, log10, sin, cos, tan, asin, acos, atan,
atan2, sinh, cosh, tanh, asinh, acosh, atanh, deg, rad, constants _pi,
_e, _tau; randomness: math.random() (0–1), math.random(max), math.random(min, max),
math.randomInt(min, max) (inclusive), math.randomSeed(n).
All randomness (dice, math.random, shuffled text) uses one generator. Seeding it
(math.randomSeed(n) or story.Random.Seed(n)) makes a playthrough repeatable on every
platform, and it’s saved with the story.
Comments and lines
// line comment
/* block
comment */
a = 1; b = 2 // several statements on one line
total = (a +
b) // inside (), [] or {} a line can continue
long = 1 + \
2 // or end a line with \
Reserved words
and break by case const continue default do else enum event extern for func if import in local new not null or pass return switch until wait while yield true false
d4, d20, 2d6, … are dice rolls, so they can’t be used as variable names.
new TypeName() is reserved: it’s disabled unless the host sets
StoryOptions.Interpreter.AllowCreateInstance.