State and Storage
The engine keeps data in several stores. Two of them go into every save: the state, which describes what’s on the screen, and the storage, which holds your game’s variables. The others live only while the page is open. This page lists each store and the methods that read and change it.
Which store to use
| Store | What it holds | In a save | Reset by a new game | Use it for |
|---|---|---|---|---|
storage() |
Your game’s variables. | Yes | Back to the values js/storage.js gives |
Everything your story remembers: the player’s name, points, flags. |
state() |
Where the game is and what’s on the screen: label, step, scene, characters, music. | Yes | Yes | Reading where the game is. The actions write it. |
history() |
What each action needs to undo itself. | Yes | Emptied | Nothing, unless you write an action. |
global() |
Values that last while the page is open: the engine’s flags and yours. | No | No | Data that must not be saved. |
temp() |
A value read once. | No | No | Handing a value from one piece of code to the next. |
The player’s preferences are apart from all of these: the engine saves them on their own, and they apply to every save.
Nothing here survives the page closing on its own: the storage and the state reach the browser’s storage only inside a save. To keep data across every save (an unlocked ending, say), write it yourself with monogatari.Storage.
The storage
storage()
Reads your game’s variables, or changes them.
storage(): object
storage(name: string): any
storage(object: object): void| Form | What it does |
|---|---|
storage() |
Returns every variable. |
storage('player') |
Returns one variable, or undefined. |
storage({ … }) |
Merges the object into the variables. Returns nothing. |
The starter game declares its variables in js/storage.js:
monogatari.storage({
player: {
name: '',
},
points: 0,
});Read and change them from a function in the script, where this is the engine:
monogatari.script({
'Start': [
function() {
this.storage({ points: this.storage('points') + 1 });
},
'y You have {{points}} points.',
'end',
],
});Yui says “You have 1 points.”
How merging works:
- Objects merge.
storage({ player: { age: 20 } })addsageand keepsplayer.name. - Arrays are replaced. After
storage({ items: ['key'] })andstorage({ items: ['map'] }),itemsis['map']. To add to a list, read it first:storage({ items: [...this.storage('items'), 'map'] }). - An empty object changes nothing.
storage({ player: {} })keeps every key ofplayer. Givenullto clear a variable:storage({ player: null }). storage('name')reads one top-level variable.storage('player.name')returnsundefined; readstorage('player').name.
Keep the values to plain data (text, numbers, true and false, null, arrays and plain objects). A save writes them to the browser’s storage, and some storage engines can’t hold anything else.
Changing a variable isn’t undone when the player goes back, unless the statement that changed it says how: Variables and Storage explains how to write a function that can be undone.
replaceVariables()
Puts the values of your variables into a text, where it has {{name}}.
replaceVariables(text: string, options?: { escapeValues?: boolean, reportMissing?: boolean }): stringmonogatari.storage({ player: { name: 'Ana' } });
monogatari.replaceVariables('Hello, {{player.name}}.'); // 'Hello, Ana.'- A dot reaches into an object:
{{player.name}}. - It first replaces
_(Key)with the interface string of the player’s language (seetranslate()). - It runs again on the result, so a value that holds
{{…}}is replaced too. A value that keeps adding variables (one that holds its own name, like{ title: 'The {{title}}' }) is read again 16 times at most; then the text is returned as it is and, with the debug module, the dialog A variable’s value keeps expanding opens. - A variable that doesn’t exist stays in the text as written, and opens an error dialog (with the debug module):
replaceVariables('Hello, {{nobody}}.')returns'Hello, {{nobody}}.'. escapeValues: trueinserts each value as text, with&,<,>and quotes escaped, for a text you put into the page as HTML. The text around the variables is left as it is.reportMissing: falseopens no dialog for a missing variable.
monogatari.storage({ player: { name: '<b>Ana</b>' } });
monogatari.replaceVariables('Hi, {{player.name}}.', { escapeValues: true }); // 'Hi, <b>Ana</b>.'The engine runs every text statement through it before it reads it, which is why {{…}} works in dialog, in character names, in the credits, and in any statement: 'show scene {{place}}' shows the scene the place variable names. It matches the statement with the values as they are, then, for a line of dialog, inserts them escaped: see Dialogs. Character names, choices, messages, inputs and the dialog log escape the values too.
The state
state()
Reads where the game is and what it shows, or changes it.
state(): object
state(key: string): any
state(object: object): object| Form | What it does |
|---|---|
state() |
Returns the whole state. |
state('label') |
Returns one value. |
state({ … }) |
Merges the object into the state, fires willUpdateState and didUpdateState, and returns the whole state. |
monogatari.state('label'); // 'Start'
monogatari.state('step'); // 2What the state holds:
| Key | Type | What it is |
|---|---|---|
label |
string |
The label the game is in. |
step |
number |
The position of the current statement in that label, from 0. |
scene |
string |
The show scene statement on the screen, or ''. |
background |
string |
The show background statement on the screen, or ''. |
characters |
string[] |
The show character statements on the screen. |
characterLayers |
string[] |
The statements that show character layers. |
images |
string[] |
The show image statements on the screen. |
videos |
string[] |
The show video statements on the screen. |
canvas |
string[] |
The show canvas statements on the screen. |
particles |
string |
The show particles statement, or ''. |
music, sound, voice |
{ statement, paused }[] |
What’s playing: each play statement and whether it’s paused. |
textboxHidden |
boolean |
Whether a hide textbox statement hid the text box. |
answeredChoice |
{ label, step, option } or null |
While the line a choice option’s Do showed is on screen, at the choice’s own step: where the choice is and the option picked. Going back from that line shows the menu again, and a save made there loads that line. |
The actions write these keys as they run and undo statements; changing them by hand doesn’t change the screen, and a save or a rollback would then rebuild a screen that doesn’t match. Keep your own data in the storage.
history()
Reads the lists the actions keep to undo themselves.
history(): object
history(key: string): array
history(object: object): voidhistory() returns every list. history('jump') returns one, and creates it (empty) if it doesn’t exist. history({ … }) replaces the lists the object names.
The lists are label, music, sound, voice, scene, background, sceneElements, sceneState, character, characterLayer, image, particle, video, canvas, nvl, clear, choice, choiceOutcome, jump, conditional, particleState, gallery and textbox. jump, for example, holds an entry for each jump, with the label and step it left and the label it went to, so going back can return there. choice holds the key of each option the player picked; choiceOutcome holds, for every choice the game went through, its label and step and the option picked, or null when every option was hidden.
A save holds the history, and a new game empties it. Your game has no reason to change it; an action of your own may keep a list here (see Extending Monogatari).
object()
Returns what a save holds of the game.
object(): { history: object; state: object; storage: object }The three values are the engine’s own objects, not copies: reading them is fine, changing them changes the game. What a save holds shows where this object goes.
Values that aren’t saved
global()
Reads or sets one value that lasts while the page is open. Saves don’t hold it, and a new game doesn’t reset it.
global(key: string): any
global(key: string, value: any): anymonogatari.global('visits', 1);
monogatari.global('visits'); // 1Setting a value returns it. A key that doesn’t exist reads as undefined, and so does a key that holds null.
The engine keeps its own flags here. Reading them is safe; changing them changes how the engine behaves.
| Key | What it says |
|---|---|
playing |
true while a game is being played (after Start or a load, until end). |
distraction_free |
true while distraction-free mode is on. |
finished_typing |
true once the current line has finished typing. |
on_splash_screen |
true while the splash screen label plays. |
_first_run |
true when the player had no saved preferences: the first time they open the game. |
_restoring_state |
true while a save loads. |
_didSetup, _didBind, _didInit |
true once each step of init() has finished. |
current_auto_save_slot |
The number of the slot the next autosave writes to. |
storageStructure |
The storage variables as they were when the game started, as JSON text. resetGame() restores them from it. |
_engine_block |
true while a proceed() or rollback() runs. |
block, _executing_sub_action |
Deprecated. Setting block still stops the game from advancing. |
The other keys (skip, _auto_play_timer, _auto_save_interval, delete_slot, overwrite_slot, _log, and the ones that start with _choice, _conditional, _dialog, _input and _scene) are the bookkeeping of single actions and screens.
globals()
Reads every global value, or changes several.
globals(): object
globals(object: object): objectWith an object, it merges it in. It returns every global value either way. Unlike global(), it shows null values as they are.
temp()
Stores a value for one read.
temp(key: string, value: any): void
temp(key: string): anyWith a value, it stores it. Without one, it returns the value and forgets it: a second read returns undefined.
monogatari.temp('lastChoice', 'red');
monogatari.temp('lastChoice'); // 'red'
monogatari.temp('lastChoice'); // undefinedtemplate()
Stores a value under a name and reads it back.
template(key: string, value?: any): anyIt returns the value. No part of the engine reads what you store here; it’s a place of your own, like global().
fn()
Stores a pair of functions under a name.
fn(name: string, functions?: { apply?: function; revert?: function }): { apply: function; revert: function }It returns the pair. A function you leave out of the object becomes one that returns true. fn('name') with no second argument reads the pair without changing it; when nothing is stored under that name, it returns a pair of functions that return true and stores nothing. No part of the engine calls these functions. For a function the script runs and can undo, use a function statement.
monogatari.fn('greet', {
apply: () => console.log('Hello'),
});
monogatari.fn('greet').apply(); // logs HelloBefore 2.9.0, fn('name') alone replaced what was stored with two functions that return true.