Skip to Content
API ReferenceVariables & Persistence

Variables & Persistence

Functions for storing and retrieving data within plugins and across sessions.


Plugin Variables

Variables are plugin-scoped storage that persists during the session. They’re useful for tracking game state, storing configuration, and sharing data between triggers.

setVariable

Store a value with a name.

API:

setVariable(name, value)
ParameterTypeRequiredDescription
namestringYesVariable name
valueanyYesValue to store

Example:

-- Store simple values setVariable("hp", 100) setVariable("maxhp", 150) setVariable("player_name", "Hero") -- Store booleans setVariable("in_combat", true) setVariable("is_resting", false) -- Store tables (serialized) setVariable("inventory", { sword = 1, potion = 5 })

getVariable

Retrieve a stored value by name.

API:

local value = getVariable(name)
ParameterTypeRequiredDescription
namestringYesVariable name to retrieve

Returns: The stored value, or nil if not found

Example:

local hp = getVariable("hp") local name = getVariable("player_name") if getVariable("in_combat") then print("Currently in combat!") utilprint("$R[Combat] $wIn progress!") end -- Check for existence local gold = getVariable("gold") if gold then print("You have " .. gold .. " gold") utilprint("$YGold: $w" .. gold) else print("Gold not tracked yet") end

deleteVariable

Remove a variable from storage.

API:

local success = deleteVariable(name)
ParameterTypeRequiredDescription
namestringYesVariable name to delete

Returns: boolean - Whether the variable was deleted

Example:

-- Clean up temporary variables deleteVariable("temp_target") deleteVariable("last_attack_time")

getAllVariables

Get all variables as a table.

API:

local vars = getAllVariables()

Returns: table - All variables as key-value pairs

Example:

local vars = getAllVariables() -- List all variables for name, value in pairs(vars) do print(name .. " = " .. tostring(value)) end -- Check total count local count = 0 for _ in pairs(vars) do count = count + 1 end print("Total variables: " .. count)

MUSHclient Compatibility

PascalCase aliases for MUSHclient script compatibility.

SetVariable

Alias for setVariable (MUSHclient compatibility).

API:

SetVariable(name, value)

When used within trigger/alias scripts, automatically converts value to string (matching MUSHclient behavior).

Example:

-- In a trigger script SetVariable("last_hp", "%1") -- Capture from trigger match

GetVariable

Alias for getVariable (MUSHclient compatibility).

API:

local value = GetVariable(name)

Example:

local lastHp = GetVariable("last_hp")

Table Persistence

Save complex data structures to localStorage for persistence between sessions.

saveTable

Save a Lua table to persistent storage.

API:

local success = saveTable(tableName, data)
ParameterTypeRequiredDescription
tableNamestringYesUnique name for this table
datatableYesTable data to save

Returns: boolean - Whether the save succeeded

Example:

-- Save player state local playerData = { name = "Hero", level = 25, class = "Warrior", skills = { "slash", "parry", "berserk" }, stats = { strength = 18, dexterity = 14, constitution = 16 } } if saveTable("player_data", playerData) then print("Player data saved!") utilprint("$G[Save] $wPlayer data saved!") else print("Failed to save player data") utilprint("$R[Error] $wFailed to save player data") end -- Save map data local visitedRooms = { ["town_square"] = { visits = 15, lastVisit = os.time() }, ["tavern"] = { visits = 8, lastVisit = os.time() } } saveTable("visited_rooms", visitedRooms) -- Save configuration local config = { autoHeal = true, healThreshold = 50, showDamageNumbers = true } saveTable("plugin_config", config)

loadTable

Load a previously saved table from persistent storage.

API:

local data = loadTable(tableName)
ParameterTypeRequiredDescription
tableNamestringYesName of the table to load

Returns: table - The saved data, or nil if not found

Example:

-- Load player data on startup local playerData = loadTable("player_data") if playerData then print("Welcome back, " .. playerData.name .. "!") print("Level " .. playerData.level .. " " .. playerData.class) utilprint("$G[Welcome] $w" .. playerData.name .. " - Level " .. playerData.level) else print("No saved data found. Starting fresh.") playerData = { name = "NewPlayer", level = 1 } end -- Load configuration with defaults local config = loadTable("plugin_config") or { autoHeal = false, healThreshold = 30, showDamageNumbers = true } -- Load visited rooms local visitedRooms = loadTable("visited_rooms") or {}

Complete Persistence Example

-- Statistics tracking plugin print("Loading stats tracker...") -- Default configuration local config = loadTable("my_plugin_config") or { autoHeal = true, healThreshold = 30, autoLoot = true } -- Default statistics local stats = loadTable("my_plugin_stats") or { kills = 0, deaths = 0, goldEarned = 0, sessionsPlayed = 0 } -- Increment session counter stats.sessionsPlayed = stats.sessionsPlayed + 1 saveTable("my_plugin_stats", stats) print("Session #" .. stats.sessionsPlayed) utilprint("$G[Session] $w#" .. stats.sessionsPlayed) -- Config command registerCommand("myconfig", function(args) if args[1] == "autoheal" then if args[2] == "on" then config.autoHeal = true saveTable("my_plugin_config", config) print("Auto-heal enabled") utilprint("$G[Config] $wAuto-heal enabled") elseif args[2] == "off" then config.autoHeal = false saveTable("my_plugin_config", config) print("Auto-heal disabled") utilprint("$Y[Config] $wAuto-heal disabled") end else print("Auto-heal: " .. tostring(config.autoHeal)) print("Heal threshold: " .. config.healThreshold .. "%") end end, "View/change config") -- Stats command registerCommand("mystats", function() print("Kills: " .. stats.kills) print("Deaths: " .. stats.deaths) print("Gold: " .. stats.goldEarned) print("Sessions: " .. stats.sessionsPlayed) utilprint("$C[Stats] $wKills: " .. stats.kills .. " | Deaths: " .. stats.deaths) end, "Show statistics") -- Track kills addTrigger("You have slain", function() stats.kills = stats.kills + 1 saveTable("my_plugin_stats", stats) end) -- Track deaths addTrigger("You have died", function() stats.deaths = stats.deaths + 1 saveTable("my_plugin_stats", stats) print("Deaths: " .. stats.deaths) utilprint("$R[Death] $wTotal deaths: " .. stats.deaths) end) -- Track gold addTrigger("You receive (%d+) gold", function(line, matches) stats.goldEarned = stats.goldEarned + tonumber(matches[1]) saveTable("my_plugin_stats", stats) end, { type = "regex" }) print("Stats tracker loaded!")

Plugin Discovery

Find and interact with other plugins in the same session.

getPluginId

Get this plugin’s unique ID.

API:

local id = getPluginId()

Returns: string - The plugin’s unique identifier

Example:

local myId = getPluginId() log("My plugin ID: " .. myId)

getPluginName

Get this plugin’s name.

API:

local name = getPluginName()

Returns: string - The plugin’s name


getPluginInfo

Get detailed info about this plugin.

API:

local info = getPluginInfo()

Returns: table - { id, name, version, author, description }


getLoadedPlugins

List all currently loaded (enabled) plugins.

API:

local plugins = getLoadedPlugins()

Returns: table - Array of { id, name, version, author, enabled }

Example:

local plugins = getLoadedPlugins() for i, p in ipairs(plugins) do log(p.name .. " v" .. p.version .. " by " .. p.author) end

findPluginByName

Find a plugin by its name.

API:

local plugin = findPluginByName(name)
ParameterTypeRequiredDescription
namestringYesPlugin name to search for (case-insensitive)

Returns: table - { id, name, version, author } or nil if not found

Example:

local combat = findPluginByName("Combat Helper") if combat then log("Found Combat Helper: " .. combat.id) end

Cross-Plugin Access

Access variables and tables from other plugins in the same session.

getPluginVariable

Get a variable from another plugin.

API:

local value = getPluginVariable(pluginId, varName)
ParameterTypeRequiredDescription
pluginIdstringYesTarget plugin’s ID
varNamestringYesVariable name to retrieve

Returns: The value, or nil if not found

Example:

-- Find the combat plugin and get its target local combat = findPluginByName("Combat Helper") if combat then local target = getPluginVariable(combat.id, "current_target") if target then log("Combat target: " .. target) end end

getPluginTable

Get a saved table from another plugin.

API:

local data = getPluginTable(pluginId, tableName)
ParameterTypeRequiredDescription
pluginIdstringYesTarget plugin’s ID
tableNamestringYesTable name to retrieve

Returns: table - The data, or nil if not found

Example:

-- Get stats from another plugin local stats = findPluginByName("Stats Tracker") if stats then local playerStats = getPluginTable(stats.id, "player_stats") if playerStats then log("Total kills: " .. playerStats.kills) end end

Plugin Broadcast System

Send messages between plugins in the same session.

broadcastPlugin

Broadcast a message to ALL plugins.

API:

broadcastPlugin(message, data)
ParameterTypeRequiredDescription
messagestringYesMessage type/name
dataanyNoAdditional data to send

Example:

-- Notify all plugins of a state change broadcastPlugin("combat_started", { target = "goblin" }) broadcastPlugin("health_low", { hp = 25, maxHp = 100 })

broadcastToPlugin

Send a message to a specific plugin.

API:

broadcastToPlugin(pluginId, message, data)
ParameterTypeRequiredDescription
pluginIdstringYesTarget plugin’s ID
messagestringYesMessage type/name
dataanyNoAdditional data to send

Example:

-- Request data from a specific plugin local healer = findPluginByName("Auto Healer") if healer then broadcastToPlugin(healer.id, "request_heal", { priority = "high" }) end

onPluginBroadcast

Listen for messages from other plugins.

API:

onPluginBroadcast(callback)
ParameterTypeRequiredDescription
callbackfunctionYesHandler: function(senderId, message, data)

Example:

-- Listen for broadcasts from other plugins onPluginBroadcast(function(senderId, message, data) if message == "combat_started" then log("Combat started by plugin " .. senderId) -- React to combat starting setVariable("in_combat", true) elseif message == "request_heal" then -- Another plugin is requesting a heal Send("cast heal") end end)

Cross-Plugin Communication Example

-- Plugin A: Combat Tracker plugin = { name = "Combat Tracker", version = "1.0" } function init() -- Track combat state addTrigger("You attack", function() setVariable("in_combat", true) setVariable("combat_target", "enemy") -- Notify other plugins broadcastPlugin("combat_started", { target = getVariable("combat_target") }) end) addTrigger("Combat over", function() setVariable("in_combat", false) broadcastPlugin("combat_ended", {}) end) end
-- Plugin B: Auto Healer (reacts to Plugin A) plugin = { name = "Auto Healer", version = "1.0" } function init() -- Listen for combat tracker events onPluginBroadcast(function(senderId, message, data) if message == "combat_started" then log("Combat detected, enabling auto-heal") setVariable("auto_heal_active", true) elseif message == "combat_ended" then log("Combat ended, disabling auto-heal") setVariable("auto_heal_active", false) end end) -- Or directly check the combat tracker's state local combat = findPluginByName("Combat Tracker") if combat then local inCombat = getPluginVariable(combat.id, "in_combat") if inCombat then log("Combat already in progress") end end end

Best Practices

Variables vs Tables

Use Variables ForUse Tables For
Simple values (hp, mana, gold)Complex nested data
Temporary session dataData that must persist between sessions
Fast access countersConfiguration settings
State flagsHistorical data / statistics

Naming Conventions

-- Use descriptive, namespaced names to avoid conflicts setVariable("combat_target_name", target) setVariable("combat_last_attack", os.time()) -- For tables, prefix with plugin name saveTable("mapper_visited_rooms", rooms) saveTable("mapper_config", config)

Error Handling

-- Always check loadTable results local data = loadTable("important_data") if not data then print("Warning: Could not load saved data") utilprint("$Y[Warning] $wCould not load saved data") data = createDefaultData() end -- Verify saveTable succeeded if not saveTable("important_data", data) then print("Error: Failed to save data!") utilprint("$R[Error] $wFailed to save data!") end
Last updated on