### story:begin Source: https://github.com/astrochili/narrator/blob/master/README.md Starts a story instance, generating the initial set of paragraphs and choices. ```APIDOC ## story:begin() ### Description Begins the story. Generates the first chunk of paragraphs and choices. ### Method `story:begin()` ### Request Example ```lua local book = require('stories.game') local story = narrator.init_story(book) local first_chunk = story:begin() ``` ### Response - **first_chunk** (table) - The initial content of the story, typically containing paragraphs and choices. ``` -------------------------------- ### Install Busted Testing Framework Source: https://github.com/astrochili/narrator/blob/master/README.md Command to install the Busted testing framework using LuaRocks, a package manager for Lua. This is a prerequisite for running tests. ```shell $ luarocks install busted ``` -------------------------------- ### Begin Story Execution (Lua) Source: https://context7.com/astrochili/narrator/llms.txt Starts the execution of a story and generates the initial chunk of content. This function must be called before any calls to 'continue' to prime the story's output queue. ```lua local narrator = require('narrator.narrator') local book = require('stories.game') local story = narrator.init_story(book) -- Begin the story (must be called before continue) story:begin() -- Now paragraphs are ready to be pulled local paragraphs = story:continue() ``` -------------------------------- ### Install Narrator with LuaRocks Source: https://github.com/astrochili/narrator/blob/master/README.md Installs the 'lpeg' dependency required for parsing Ink content using LuaRocks. This is necessary for development when generating Lua versions of books. ```shell $ luarocks install lpeg ``` -------------------------------- ### Implement Story State Migration in Lua Source: https://context7.com/astrochili/narrator/llms.txt This example demonstrates how to handle version upgrades for game save files using a custom migration function. It shows renaming variables, type conversion, adding default variables, and removing deprecated ones. The migration function is assigned to 'story.migrate' before loading the state. ```lua local narrator = require('narrator.narrator') local book = require('stories.game') local story = narrator.init_story(book) -- Define migration function local function migrate_save(state, old_version, new_version) -- No migration needed if versions match if old_version == new_version then return state end -- Migrate from version 1 to 2 if old_version == 1 and new_version >= 2 then -- Rename variable if state.variables['old_name'] then state.variables['new_name'] = state.variables['old_name'] state.variables['old_name'] = nil end -- Convert number to string if type(state.variables['mood']) == 'number' then local mood_value = state.variables['mood'] state.variables['mood'] = mood_value > 50 and 'happy' or 'sad' end end -- Migrate from version 2 to 3 if old_version == 2 and new_version >= 3 then -- Add new required variables with defaults state.variables['difficulty'] = state.variables['difficulty'] or 'normal' -- Remove deprecated variables state.variables['old_system'] = nil end return state end -- Assign migration function before loading story.migrate = migrate_save -- Load old save file local old_save = load_save_file('player_save.dat') story:load_state(old_save) -- Migration happens automatically during load_state -- Continue playing with migrated state local paragraphs = story:continue() ``` -------------------------------- ### Get Available Choices - Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Retrieves an array of available choices for the player. Returns an empty array if the story has paragraphs to continue. Each choice is a table containing text and optional tags. ```lua -- Get available choices and output them to the player local choices = story:get_choices() for i, choice in ipairs(choices) do print(i .. ') ' .. choice.text) end ``` -------------------------------- ### Get Tags for a Story Path - Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Retrieves tags associated with a given story path (e.g., 'knot.stitch'). This is useful for inspecting tags before advancing the story. ```lua -- Get tags for the path 'adventure.maze' local mazeTags = story:get_tags('adventure.maze') ``` -------------------------------- ### Complete Game Loop with Narrator in Lua Source: https://context7.com/astrochili/narrator/llms.txt This Lua script implements a full interactive narrative game loop using the Narrator library. It includes parsing narrative files (or loading pre-parsed modules), initializing the story, binding external functions for game integration (like playing music, adding items, checking inventory), observing story variables for reactive updates, and managing the main game loop with player choices, saving, and loading functionality. This example showcases Narrator's capabilities for complex branching narratives and state management. ```lua local narrator = require('narrator.narrator') -- Parse and save book during development -- local book = narrator.parse_file('stories.game', { save = true }) -- In production, load pre-parsed book local book = require('stories.game') local story = narrator.init_story(book) -- Setup game integration local player_inventory = {} local audio_system = require('audio') -- Bind external functions story:bind('play_music', function(track) audio_system.play_music(track) end) story:bind('add_item', function(item) table.insert(player_inventory, item) print('Received: ' .. item) end) story:bind('has_item', function(item) for _, inv_item in ipairs(player_inventory) do if inv_item == item then return true end end return false end) -- Observe variables story:observe('scene', function(scene_name) print('=== Scene: ' .. scene_name .. ' ===') end) story:observe('reputation', function(rep) if rep >= 100 then print('Achievement unlocked: Beloved Hero!') end end) -- Begin story story:begin() print('=== Game Started ===\n') -- Main game loop while story:can_continue() do -- Display paragraphs local paragraphs = story:continue() for _, paragraph in ipairs(paragraphs) do local text = paragraph.text -- Handle tags if paragraph.tags then text = text .. ' #' .. table.concat(paragraph.tags, ' #') end print(text) end -- Check for game over if not story:can_choose() then break end print('') -- Display choices local choices = story:get_choices() for i, choice in ipairs(choices) do local choice_text = i .. ') ' .. choice.text if choice.tags then choice_text = choice_text .. ' [' .. table.concat(choice.tags, ', ') .. ']' end print(choice_text) end -- Get player input print('') io.write('Choose (or "save"/"load"): ') local input = io.read() -- Handle save/load if input == 'save' then local state = story:save_state() local file = io.open('savegame.lua', 'w') file:write('return ' .. require('narrator.libs.lume').serialize(state)) file:close() print('Game saved!\n') elseif input == 'load' then local state = dofile('savegame.lua') story:load_state(state) print('Game loaded!\n') else -- Make choice local choice_index = tonumber(input) or 0 if choice_index > 0 and choice_index <= #choices then story:choose(choice_index) print('') else print('Invalid choice!\n') end end end print('\n=== Game Over ===') print('Final inventory: ' .. table.concat(player_inventory, ', ')) print('Final score: ' .. (story.variables['score'] or 0)) ``` -------------------------------- ### Continue Story and Get Paragraphs (Lua) Source: https://context7.com/astrochili/narrator/llms.txt Retrieves paragraphs from the story's output queue. It can fetch all available paragraphs, a specific number, or one at a time. Each paragraph object contains text and optional tags, facilitating the display of narrative content and associated metadata. ```lua local narrator = require('narrator.narrator') local book = require('stories.game') local story = narrator.init_story(book) story:begin() -- Get all available paragraphs while story:can_continue() do local paragraphs = story:continue() for _, paragraph in ipairs(paragraphs) do print(paragraph.text) if paragraph.tags then for _, tag in ipairs(paragraph.tags) do print(' Tag: ' .. tag) end end end end -- Get one paragraph at a time if story:can_continue() then local paragraph = story:continue(1) print(paragraph.text) end -- Get specific number of paragraphs local three_paragraphs = story:continue(3) ``` -------------------------------- ### Get Visit Count for a Story Path - Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Returns the number of times a specific path within the story has been visited. The path is specified as a string (e.g., 'knot.stitch.label'). ```lua -- Get the number of visits to the maze's red room local red_room_visits = story:get_visits('adventure.maze.red_room') -- Get the number of adventures visited. local adventure_visits = story:get_visits('adventure') ``` -------------------------------- ### Require Narrator Module in Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Loads the Narrator module in a Lua environment. This is a common step after installation to make the Narrator library available for use. ```lua local narrator = require('narrator.narrator') ``` -------------------------------- ### Get Story Paragraphs - Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Retrieves the next set of paragraphs from the story. You can specify the number of paragraphs to fetch. If no argument is provided or 0 is passed, all available paragraphs are returned. Passing 1 returns a single paragraph without wrapping it in an array. ```lua -- Get all the currently available paragraphs local paragraphs = story:continue() -- Get one next paragraph local paragraph = story:continue(1) ``` -------------------------------- ### Jump to Story Paths in Narrator (Lua) Source: https://context7.com/astrochili/narrator/llms.txt Navigate to specific points within a story using knot, stitch, or label paths. This function is essential for controlling the narrative flow and guiding the player through different story segments. It takes a string path as input and updates the story's current position. ```lua local narrator = require('narrator.narrator') local book = require('stories.game') local story = narrator.init_story(book) story:begin() -- Jump to a knot story:jump_to('adventure') -- Jump to a stitch within a knot story:jump_to('adventure.forest') -- Jump to a label story:jump_to('adventure.forest.treasure_room') -- Continue after jumping local paragraphs = story:continue() for _, p in ipairs(paragraphs) do print(p.text) end ``` -------------------------------- ### Get Visit Counts for Story Locations (Lua) Source: https://context7.com/astrochili/narrator/llms.txt Retrieve the number of times a specific story location (knot, stitch, or label) has been visited. This is useful for tracking player progress, implementing conditional events based on visit frequency, or providing statistics. The function accepts a string path and returns an integer count. ```lua local narrator = require('narrator.narrator') local book = require('stories.game') local story = narrator.init_story(book) story:begin() story:continue() -- Get visits to a knot local knot_visits = story:get_visits('adventure') print('Visited adventure ' .. knot_visits .. ' times') -- Get visits to a stitch local stitch_visits = story:get_visits('adventure.forest') print('Visited forest ' .. stitch_visits .. ' times') -- Get visits to a label local label_visits = story:get_visits('adventure.forest.treasure_room') print('Found treasure room ' .. label_visits .. ' times') ``` -------------------------------- ### narrator.init_story Source: https://github.com/astrochili/narrator/blob/master/README.md Initializes a story instance from a pre-parsed book object. ```APIDOC ## narrator.init_story(book) ### Description Inits a story instance from the book. This is actual to use in production. For example, just load a book with `require()` and pass it to this function. ### Method `narrator.init_story(book)` ### Parameters - **book** (table) - Required - The parsed book instance. ### Request Example ```lua -- Require a parsed and saved before book local book = require('stories.game') -- Init a story instance local story = narrator.init_story(book) ``` ### Response - **story** (table) - An initialized story instance. ``` -------------------------------- ### Initialize Story Instance from Book (Lua) Source: https://github.com/astrochili/narrator/blob/master/README.md Initializes a story instance from a pre-parsed book. This function is intended for production use, typically after loading a saved book instance using `require()`. ```lua -- Require a parsed and saved before book local book = require('stories.game') -- Init a story instance local story = narrator.init_story(book) ``` -------------------------------- ### Begin Story Execution (Lua) Source: https://github.com/astrochili/narrator/blob/master/README.md Initiates the execution of a story. This function generates the initial set of paragraphs and available choices for the player to interact with. ```lua -- Begins the story. Generates the first chunk of paragraphs and choices. local story = narrator.init_story(book) story:begin() ``` -------------------------------- ### Initialize Story from Book (Lua) Source: https://context7.com/astrochili/narrator/llms.txt Creates an independent 'story' instance from a parsed 'book' object. Each 'story' instance maintains its own state, allowing for multiple, independent narrative playthroughs to exist concurrently from the same book data. ```lua local narrator = require('narrator.narrator') local book = require('stories.game') -- Initialize a new story local story = narrator.init_story(book) -- Multiple independent stories can exist from the same book local story1 = narrator.init_story(book) local story2 = narrator.init_story(book) ``` -------------------------------- ### Run Tests with Busted Source: https://github.com/astrochili/narrator/blob/master/README.md Command to execute tests using the Busted framework. It points to the main test runner script located at 'test/run.lua'. ```shell $ busted test/run.lua ``` -------------------------------- ### Add Narrator and Defold-lpeg Dependencies for Defold Source: https://github.com/astrochili/narrator/blob/master/README.md Specifies the GitHub repository URLs for Narrator and defold-lpeg as dependencies in a Defold project. This allows Defold to manage and include these libraries. ```plaintext https://github.com/astrochili/narrator/archive/master.zip https://github.com/astrochili/defold-lpeg/archive/master.zip ``` -------------------------------- ### Implement Story Migration Function in Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Provides a Lua function for migrating game states between different book versions. It allows renaming or changing variables and updating paths to ensure save compatibility after game updates. The default implementation does nothing. ```lua -- Default implementation function(state, old_version, new_version) return state end ``` ```lua -- A migration function example local function migrate(state, old_version, new_version) -- Check the need for migration if new_version == old_version then return state end -- Migration for the second version of the book if new_version == 2 then -- Get the old value local old_mood = state.variables['mood'] -- If it exists then migrate ... if old_mood then -- ... migrate the old number value to the new string value state.variables['mood'] = old_mood < 50 and 'sadly' or 'sunny' end end return state end -- Assign the migration function before loading a saved game story.migrate = migrate -- Load the game story:load_state(saved_state) ``` -------------------------------- ### Lua: Parse Ink file and play story Source: https://github.com/astrochili/narrator/blob/master/README.md This snippet demonstrates how to use the Narrator library in Lua to parse an Ink file into a 'book' (Lua table), initialize a 'story' runtime from it, and then play through the narrative. It shows how to retrieve and print paragraphs, handle tags, present choices to the player, and process player input to advance the story. This is the core usage pattern for integrating Ink narratives into Lua applications. ```lua local narrator = require('narrator.narrator') -- Parse a book from the Ink file. local book = narrator.parse_file('stories.game') -- Init a story from the book local story = narrator.init_story(book) -- Begin the story story:begin() while story:can_continue() do -- Get current paragraphs to output local paragraphs = story:continue() for _, paragraph in ipairs(paragraphs) do local text = paragraph.text -- You can handle tags as you like, but we attach them to text here. if paragraph.tags then text = text .. ' #' .. table.concat(paragraph.tags, ' #') end -- Output text to the player print(text) end -- If there is no choice it seems like the game is over if not story:can_choose() then break end -- Get available choices and output them to the player local choices = story:get_choices() for i, choice in ipairs(choices) do print(i .. ') ' .. choice.text) end -- Read the choice from the player input local answer = tonumber(io.read()) -- Send answer to the story to generate new paragraphs story:choose(answer) end ``` -------------------------------- ### Make Choice and Continue Narrative (Lua) Source: https://context7.com/astrochili/narrator/llms.txt Handles player choices within the narrative. It allows checking for available choices, displaying them to the player, and processing the player's selection to advance the story. After a choice is made, the narrative continues, and new paragraphs can be retrieved. ```lua local narrator = require('narrator.narrator') local book = require('stories.game') local story = narrator.init_story(book) story:begin() -- Display all paragraphs local paragraphs = story:continue() for _, p in ipairs(paragraphs) do print(p.text) end -- Check if choices are available if story:can_choose() then local choices = story:get_choices() -- Display choices for i, choice in ipairs(choices) do print(i .. ') ' .. choice.text) if choice.tags then print(' Tags: ' .. table.concat(choice.tags, ', ')) end end -- Get player input local answer = tonumber(io.read()) -- Make the choice story:choose(answer) -- Continue with new paragraphs local new_paragraphs = story:continue() end ``` -------------------------------- ### Access and Modify Story Variables in Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Demonstrates how to read and write variables within the story's state using Lua. This is essential for managing game data and player progress. ```lua -- Get the mood variable value local mood = story.variables['mood'] -- Set the mood variable value story.variables['mood'] = 'sunny' ``` -------------------------------- ### Save and Load Story State (Lua) Source: https://context7.com/astrochili/narrator/llms.txt Implement save game functionality by serializing and restoring the current state of the story. The `save_state` function returns a serializable table, which can then be loaded back into a new story instance using `load_state`. This is crucial for persistent player progress. ```lua local narrator = require('narrator.narrator') local book = require('stories.game') local story = narrator.init_story(book) story:begin() story:continue() story:choose(1) story:continue() -- Save the current state local saved_state = story:save_state() -- saved_state is a table that can be serialized to JSON or other formats -- Store state (example using pseudo storage API) local json = require('json') local file = io.open('savegame.json', 'w') file:write(json.encode(saved_state)) file:close() -- Later, load the state local file = io.open('savegame.json', 'r') local json_data = file:read('*all') file:close() local loaded_state = json.decode(json_data) -- Restore story to saved state local new_story = narrator.init_story(book) new_story:load_state(loaded_state) -- Continue from where we left off local paragraphs = new_story:continue() ``` -------------------------------- ### Observe Variable Changes in Narrator (Lua) Source: https://context7.com/astrochili/narrator/llms.txt Set up callback functions to react dynamically to changes in story variables. The `observe` function takes a variable name and a callback function, which is executed whenever the specified variable's value is updated. This enables real-time game logic adjustments. ```lua local narrator = require('narrator.narrator') local book = require('stories.game') local story = narrator.init_story(book) -- Set up observers before beginning story:observe('health', function(new_health) print('Health changed to: ' .. new_health) if new_health <= 0 then print('Player died!') end end) story:observe('mood', function(new_mood) print('Mood is now: ' .. new_mood) -- Update character sprite based on mood end) story:observe('player_name', function(name) print('Player name set to: ' .. name) end) -- As the story runs, observers are called automatically story:begin() story:continue() ``` -------------------------------- ### Parse Ink File to Book (Lua) Source: https://context7.com/astrochili/narrator/llms.txt Parses an Ink script file from disk, handling inclusions and returning a 'book' object. This book can be saved as a Lua module for production use, allowing for faster loading by directly requiring the pre-parsed module. ```lua local narrator = require('narrator.narrator') -- Parse an Ink file local book = narrator.parse_file('stories.game') -- Parse and save as Lua module for production local book = narrator.parse_file('stories.game', { save = true }) -- This creates 'stories/game.lua' that can be required later -- In production, just require the pre-parsed book local book = require('stories.game') ``` -------------------------------- ### Make a Choice - Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Allows the player to make a choice by providing its index. This function advances the story. It will not perform any action if `can_continue()` returns false. ```lua -- Get the answer from the player in the terminal answer = tonumber(io.read()) -- Send the answer to the story to generate new paragraphs story:choose(answer) -- Get the new paragraphs local new_paragraphs = story:continue() ``` -------------------------------- ### Access and Modify Story Variables in Lua Source: https://context7.com/astrochili/narrator/llms.txt This snippet shows how to read and write story variables and constants directly from Lua. It covers initializing the story, accessing constants and variables, modifying variables, and persisting the state. Assumes 'narrator.narrator' and a story book are available. ```lua local narrator = require('narrator.narrator') local book = require('stories.game') local story = narrator.init_story(book) story:begin() -- Read constants (defined with CONST in Ink) local theme = story.constants['theme'] local max_health = story.constants['MAX_HEALTH'] print('Game theme: ' .. theme) -- Read variables local player_health = story.variables['health'] local player_score = story.variables['score'] -- Modify variables from Lua story.variables['health'] = 100 story.variables['gold'] = story.variables['gold'] + 50 story.variables['inventory_full'] = true -- Variables are persisted in save state local state = story:save_state() -- state.variables contains all current variable values ``` -------------------------------- ### Jump to a Specific Story Path - Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Navigates the story to a specified path, defined by a string like 'knot.stitch.label'. After jumping, you can retrieve new paragraphs using `story:continue()`. ```lua -- Jump to the maze stitch in the adventure knot story:jump_to('adventure.maze') -- Get the maze paragraphs local maze_paragraphs = story:continue() ``` -------------------------------- ### Load Story State - Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Restores the story's state from a previously saved state. This function is used to load a game. ```lua -- Load the state from your local storage local state = manager.load() -- Restore the story's state story:load_state(state) ``` -------------------------------- ### Check if Story Can Present Choices - Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Checks if the story has choices available for the player. It returns false if there are still paragraphs to be displayed. ```lua if story:can_choose() do -- Get choices? end ``` -------------------------------- ### Access Global Tags - Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Retrieves an array containing the global tags defined for the entire story. These tags apply across the narrative. ```lua -- Get the global tags local global_tags = story.global_tags -- A hacky way to get the same global tags local global_tags = story:get_tags() ``` -------------------------------- ### Parse Ink Content from String (Lua) Source: https://context7.com/astrochili/narrator/llms.txt Parses Ink script content directly from strings, which is useful when managing files via engine-specific APIs or when the standard Lua 'io' module is unavailable. It supports basic content parsing and can also handle inclusions when provided with a table of inclusion content. ```lua local narrator = require('narrator.narrator') -- Parse simple Ink content local content = [[ Hello, world! * Yes -> knot_a * No -> knot_b === knot_a You said yes! -> END === knot_b You said no! -> END ]] local book = narrator.parse_content(content) -- Parse with inclusions local main_content = [[ INCLUDE chapter1.ink Start of story -> chapter1 ]] local inclusion_content = [[ === chapter1 First chapter text -> END ]] local book = narrator.parse_content(main_content, { inclusion_content }) ``` -------------------------------- ### Retrieve Tags from Story Locations (Lua) Source: https://context7.com/astrochili/narrator/llms.txt Fetch tags associated with specific story paths before or during traversal. Tags can be used to trigger specific game mechanics, like enabling a flashlight in a dark area or loading combat music. This function takes a path string and returns a table of associated tags. ```lua local narrator = require('narrator.narrator') local book = require('stories.game') local story = narrator.init_story(book) -- Get global tags (defined at top of Ink file) local global_tags = story.global_tags for _, tag in ipairs(global_tags) do print('Global: ' .. tag) end -- Get tags for a specific path local knot_tags = story:get_tags('adventure') local stitch_tags = story:get_tags('adventure.forest') -- Use tags to control game behavior for _, tag in ipairs(stitch_tags) do if tag == 'dark_area' then -- Enable flashlight in game elseif tag == 'combat_zone' then -- Load combat music end end ``` -------------------------------- ### Check if Story Can Continue - Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Determines if the story has more paragraphs to output. This function is typically used in a loop to control story progression. ```lua while story:can_continue() do -- Get paragraphs? end ``` -------------------------------- ### narrator.parse_file Source: https://github.com/astrochili/narrator/blob/master/README.md Parses an Ink file from the given path, including any nested inclusions. It can optionally save the parsed book to a Lua file. ```APIDOC ## narrator.parse_file(path, params) ### Description Parses the Ink file at path with all the inclusions and returns a book instance. Path notations `'stories/game.ink'`, `'stories/game'` and `'stories.game'` are valid. You can save a parsed book to the lua file with the same path by passing `{ save = true }` as `params` table. By default, the `params` table is `{ save = false }`. ### Method `narrator.parse_file(path, params)` ### Parameters - **path** (string) - Required - The path to the Ink file. - **params** (table) - Optional - A table for configuration. If `{ save = true }`, the parsed book will be saved to a Lua file. - **save** (boolean) - Optional - If true, saves the parsed book to a Lua file. Defaults to `false`. ### Request Example ```lua -- Parse a Ink file at path 'stories/game.ink' local book = narrator.parse_file('stories.game') -- Parse a Ink file at path 'stories/game.ink' -- and save the book at path 'stories/game.lua' local book = narrator.parse_file('stories.game', { save = true }) ``` ### Response - **book** (table) - A parsed book instance. ### Notes Reading and saving files requires the `io` module. If file operations are not possible, use `narrator.parse_content()`. ``` -------------------------------- ### Bind External Lua Functions to Narrator (Lua) Source: https://context7.com/astrochili/narrator/llms.txt Expose custom Lua functions to be callable from within Ink scripts. This allows game logic, such as playing sounds, managing inventory, or performing calculations, to be integrated seamlessly with the narrative. Functions can accept multiple arguments and return values. ```lua local narrator = require('narrator.narrator') local book = require('stories.game') local story = narrator.init_story(book) -- Bind function without return value story:bind('play_sound', function(sound_name) -- Your audio system audio.play(sound_name) end) -- Bind function with return value story:bind('calculate_damage', function(base_damage, armor) local damage = math.max(0, base_damage - armor) return damage end) -- Bind function with multiple parameters story:bind('add_item', function(item_name, quantity) inventory[item_name] = (inventory[item_name] or 0) + quantity print('Added ' .. quantity .. 'x ' .. item_name) end) -- Bind function returning boolean story:bind('has_key', function(key_name) return inventory[key_name] ~= nil end) -- In Ink, call these functions: -- ~ play_sound("door_open") -- You deal {calculate_damage(10, 3)} damage! -- ~ add_item("gold", 50) -- { has_key("red_key"): You unlock the door | The door is locked } story:begin() ``` -------------------------------- ### Parse Ink File with Narrator (Lua) Source: https://github.com/astrochili/narrator/blob/master/README.md Parses an Ink file located at the specified path and returns a book instance. The function supports various path notations and can optionally save the parsed book to a Lua file. ```lua -- Parse a Ink file at path 'stories/game.ink' local book = narrator.parse_file('stories.game') -- Parse a Ink file at path 'stories/game.ink' -- and save the book at path 'stories/game.lua' local book = narrator.parse_file('stories.game', { save = true }) ``` -------------------------------- ### narrator.parse_content Source: https://github.com/astrochili/narrator/blob/master/README.md Parses a string containing Ink content and returns a book instance. It can also accept an array of strings for included Ink content. ```APIDOC ## narrator.parse_content(content, inclusions) ### Description Parses the string with Ink content and returns a book instance. The `inclusions` param is optional and can be used to pass an array of strings with Ink content of inclusions. ### Method `narrator.parse_content(content, inclusions)` ### Parameters - **content** (string) - Required - The string containing the Ink content. - **inclusions** (array of strings) - Optional - An array of strings, where each string is the Ink content of an inclusion. ### Request Example ```lua local content = 'Content of a root Ink file' local inclusions = { 'Content of an included Ink file', 'Content of another included Ink file' } -- Parse a string with Ink content local book = narrator.parse_content(content) -- Parse a string with Ink content and inclusions local book = narrator.parse_content(content, inclusions) ``` ### Response - **book** (table) - A parsed book instance. ### Notes Content parsing is useful when managing files via the engine's environment without using the `io` module, such as loading Ink files as custom resources in Defold. ``` -------------------------------- ### Observe Variable Changes - Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Assigns a callback function (observer) to a specific story variable. The observer function will be executed whenever the variable's value changes. ```lua local function x_did_change(x) print('The x did change! Now it\'s ' .. x) end -- Start observing the variable 'x' story:observe('x', x_did_change) ``` -------------------------------- ### Save Story State - Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Generates a table representing the current state of the story, which can be saved for later restoration. This is used for implementing save game functionality. ```lua -- Get the story's state local state = story:save_state() -- Save the state to your local storage manager.save(state) ``` -------------------------------- ### Access Story Constants - Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Provides access to a table of constants defined within the Ink story. These values are intended for reading and should not be modified. ```lua -- Get the theme value from the Ink constants local theme = story.constants['theme'] ``` -------------------------------- ### Parse Ink Content String with Narrator (Lua) Source: https://github.com/astrochili/narrator/blob/master/README.md Parses a string containing Ink content and returns a book instance. This method is useful when file I/O is not desired or managed by the engine, such as loading Ink files as custom resources. ```lua local content = 'Content of a root Ink file' local inclusions = { 'Content of an included Ink file', 'Content of another included Ink file' } -- Parse a string with Ink content local book = narrator.parse_content(content) -- Parse a string with Ink content and inclusions local book = narrator.parse_content(content, inclusions) ``` -------------------------------- ### Bind External Function to Story - Lua Source: https://github.com/astrochili/narrator/blob/master/README.md Makes an external Lua function callable from within the Ink narrative. The bound function can optionally return a value. ```lua local function beep() print('Beep! 😃') end local function sum(x, y) return x + y end -- Bind the function without params and returned value story:bind('beep', beep) -- Bind the function with params and returned value story:bind('sum', sum) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.