Manual:Technical Manual
Note: Would you like a section-by-section view of the manual instead? See here.
Multi Session Gaming
Mudlet lets you play several simultaneous game sessions. However, currently we have the restriction that you cannot use the same profile twice. Consequently, if you want to play three characters on the same game at the same time, you need to make 3 profiles with 3 different names e.g. ernie@avalon.de, bert@avalon.de etc.
Each profile will be shown in a new tab as a session of its own. That means, your old session will not be stopped, when you start a second one. When you have more than one active session, try clicking the menu button "MultiView" to see them all together.
You can switch between profiles (characters) by pressing Ctrl+Tab
or select a particular one with Ctrl+<number of tab>
.
Want to be able to control all your profiles at once for games that allow multiplaying? Check out a package just for this. On Mudlet 4.10 and earlier, a pre-installed send-to-all-profiles
package provided control through the :<command> alias.
Split Screen
Mudlet has a split screen: if you scroll up in the game text screen (or any other mini console window), the screen will split in two parts. The lower part will follow the game output while the upper part will stay focused on your scrolling: this way you can read easier through old passages without missing what is going on at the moment. Split screen can be activated via the scroll bar, page up / page down keys or the mouse wheel.
Scrolling back to the end will close the split screen automatically. A click on the middle mouse button will close the split screen immediately as well as pressing Ctrl+Enter
on the keyboard (command+return
for mac). The size of the 2 parts of the split screen can be modified by dragging the separator bar in the middle with the mouse. Split screen can be helpful when selecting text in order to copy it to trigger editor e.g. when making triggers. If you don’t use split screen when selecting text, new arriving text will upset your selection.
To scroll quicker, hold Ctrl
while scrolling. Conversely, to scroll just one line at a time hold Shift
(available in Mudlet 4.11+).
Automatic login
If your game takes in the characters name first and the characters password afterward, Mudlet can automatically login for you. To make use of this, put the name and password into the Connection information for your profile.
By since Mudlet 4.2, all passwords by default are stored securely in the computers credential store - which means you can't just open up the file with the password and look at it. When the password is stored securely on the computer, you can find it in the credential manager - see screenshots on the left for Windows/Linux/macOS.
The drawback of storing the password on the computer itself, however, is that if you use cloud sync for your profiles - the password won't the syncronised. You can go to Special Options in settings and change the password to be stored within the profile to make that work, if you'd like the password to be portable but visible in plaintext.
Command Line Auto-Completion, Tab-Completion and Command History
Mudlets command line is especially designed for playing MUD and MUSH games. It aims at reducing the amount of typing by using autocompletion and tab completion schemes that are optimized for typical game playing situations. The command line offers tab completion (TAB key with or without shift) and autocompletion (cursor up and cursor down keys).
Tab completion searches the last 100 lines in the game output buffer for words matching the word that you are currently typing. This is useful if you have to type complicated long names. You only have to type the first letters and then press the tab key until the proposal is what you want.
Autocompletion tries to match your current typing with your command history. Example: If you typed the same command a while ago, you only have to start typing the first couple of letters and then press the cursor up key until the proposal matches the command that you want to use.
Command history - if you haven’t started to type anything yet, you can browse through your command history with the cursor up and cursor down keys. However, if you have started typing pressing cursor up will result in a shot at autocompletion.
Escape key - to get out of autocompletion you can press the ESC key any time. After pressing ESC the entire text gets selected and you can overwrite it or get back into command history mode.
Logging Output to text or HTML Log Files
Press on the little button with the blue folder with the green arrow icon on the lower right side of the command line to turn on plain text logging. Click again to stop logging. This will inform you about the file name and path of the log file. If you want to log in color you can chose to log to files in html format, but note that due to the nature of HTML, these log files tend to get very large quickly.
Log files can be found at the Mudlet home directory in your profile directory. To get the path to your Mudlet home directory you can type in your main window:
lua getMudletHomeDir()
Log files are stored in "<mudletHomeDir>/logs". Each profile has its own <mudletHomeDir> path. Log files have a similar naming convention to the autosaved profiles: date#time.txt or date#time.html
Using Variables in Mudlet
One of the major design goals in Mudlet was to integrate scripts and variables into triggers/aliases/buttons etc. as seamlessly as possible. The usage of variables in Mudlet is distinctly different from the other major clients, as native Lua scripting has been integrated into Mudlet from the ground up. As scripts are so closely intertwined with the core of Mudlet, variables do not need any special treatment as in other clients i.e. there is no need for code such as:
totalKills = getVariable("killedMonsters") + getVariable("killedVillains")
echo( "kills=" .. totalKills )
In Mudlet, the above code translates into:
totalKills = killedMonsters + killedVillains
echo( "kills=" .. totalKills )
If you define a variable in any given script in Mudlet, be it a trigger, a button, an alias key, an event handler, a free function, etc. It can be used from within any context without any special getVariable() type of function or any special variable symbols, such as @myVar etc.. In Mudlet all variables are native Lua variables. Each session (= profile/connection tab) runs in its own dedicated Lua interpreter. Consequently, all scripts of a profile are compiled into the same Lua interpreter and thus their code runs in the same variable space. All scripts from another simultaneously opened profile will not interfere because each profile uses its own Lua interpreter. Note Everything shares the same variables & functions.
To give you an example: Let’s make a little trigger that counts how many monsters you have killed. Each time you have made a new kill, the trigger matches on the kill message and runs a little script that increases the amount of kills by one each time the trigger fires - in other words, each time you kill a monster and the kill message is sent from the MUD. For the kill counter we declare a variable and call it myKills. This variable is going to hold the number of kills we’ve made so far. The script will look like this:
myKills = myKills + 1
Then we add a little alias, a button or a keybindings that executes another little script that prints your current kill statistics on the screen. The attached script would look like this:
echo( "I have killed " .. myKills .. " monsters today." )
Lua variables can be either a string of letters (aka string
) or a number
, among a few others. They are whatever there were initially created with or what data type they can be converted to.
a = "Jim"
b = "Tom"
c = 350
d = 1
--Then you can write:
e = c + d -- and e will equal 351
e = a .. b -- and e will equal "JimTom"
e = a .. c -- and e will equal "Jim350"
Note: You can't use a + b to concatenate string values. For this you must use the double-dot: ..
However, starting with Mudlet 4.11.0 we have included the f function to perform string interpolation. This is a very fancy way of saying "replacing code in strings with their value". When you run a string through the f function then it replaces anything inside a pair of {} with the value of the variable or outcome of the expression. To expand upon the example above:
a = "Jim"
b = "Tom"
c = 350
d = 1
function simple_addition(a,b)
return a+b
end
--Then you can write:
e = c + d -- and e will equal 351 (no change here)
e = f"{c + d}" -- end e will equal "351". This is a string, not a number, if you need to do math with e then do it like above.
e = f"{simple_addition(c,d)}" -- same as above, but shows using the function we've defined.
e = f("{a}{b}") -- and e will equal "JimTom"
e = f"{a}{c}" -- and e will equal "Jim350"
A shrewd observer might notice that I have written the above uses of f without the usual parentheses. In Lua you can omit the () when you are only passing a single string argument to the function. It is usually considered best practice to include the () but in the case of f for interpolation I find it reads a bit better without them. As shown in the example above it works with or without them in place.
For a more 'real world' example and comparison of concatenation, f, and string.format consider the following:
-- For the following, we assume the following variables exist:
-- target which holds the target's name
-- target_health_color which is a cecho color determined elsewhere
-- target_health which is the actual health the target has.
-- this function uses the concatenation operator .. to glue strings together for display
function displayTarget()
local msg = "\n<green>Target:<r> " .. target .. " <green>Health:<r> " .. target_health_color .. target_health
cecho(msg)
end
-- this function does the same thing, but uses f
function displayTarget()
local msg = f"\n<green>Target:<r> {target} <green>Health:<r> {target_health_color}{target_health}"
cecho(msg)
end
There is another form of variables in Lua called tables which can be used for lists, arrays or dictionaries. This is explained later. For an in-depth coverage of variables in Lua take a look at a Lua tutorial e. g. this one on numbers http://Lua-users.org/wiki/NumbersTutorial and this one on strings http://Lua-users.org/wiki/StringsTutorial or this one on Lua tables http://Lua-users.org/wiki/TablesTutorial
Let’s get back to our example. The trigger script expects myKills to be a number so you have to initialze the variable myKills to 0 before running the script for the first time. The best place to initialize variables is in script script outside of a function definition as this code is executed when the session is loaded or if you compile the script again after you have edited it. To do this click on the "Scripts" icon and select the standard script "My Global Variable Definitions". If you are using an older version of Mudlet or a profile that doesn’t have this script item, simply click on the "Add" icon and make your own script. You can call it whatever you want to. Add following code to initialize your new variable myKills to a number and set its value to 0:
myKills = 0
Whenever you edit this script, it will be recompiled and the code will be run as it is not part of a function definition. This is the major difference between trigger-scripts, alias-scripts etc. and script-scripts. Script-scripts can contain an unlimited amount of function definitions and also free code i. e. code outside of a function definition - code that is not enclosed by function xyz() …. end. On saving the script the script gets compiled and the free code is run instantly. All other item scripts, i. e. trigger-scripts etc., secretly define a function name for the script and thus the script is not free code, but function code. When a trigger fires Mudlet calls this invisible function name to run the script e.g. trigger738(), button82(), alias8(). This means that if you define variables inside a trigger script the variable will not be defined before the trigger runs for the first time. However, if you define this variable as free code in a script-script the definition becomes available immediately on script save. Now, whenever you add new variables to your variable definition script, the script gets run and your old variables will be reinitialized and reset to 0. This will be no big problem in most cases as you won’t work on your systems while really playing in most cases. To solve this problem you have two options:
First option: Add a script group (a folder) and add a new script item for each variable you define. This way, editing a variable definition will only reset the edited variable and none of the others that are defined in different scripts. This has the added advantage that you have a nice graphical overview of your defined variables. Note Organize your variables
Second option (more advanced): Change the variable initialization to only initialize the variable if it hasn’t been initialized before, thus keeping the values of previously defined variables. The following code initializes the variable myKills (to the number 0) but only if it hasn't been initialized before. This would look like this:
if myKills == nil then
myKills = 0
end
In Lua all undefined variables are initialized to the value nil. The value nil is not the same thing as the number 0 or the empty string "". What it means is that a variable that has the value nil has not been declared yet and does not exist. If a variable does not exist, it cannot be used as its value is undefined at this point. Consequently, increasing the value of nil by one is impossible as the variable doesn’t exist yet and will lead to a Lua error. The above script simply checks if the variable myKills has been defined yet and if it hasn’t, it will declare the variable and set its value to 0.
Tables as Lists
Having variables that hold a single value is the most important usage of variables, but very often you’ll like to define variables that hold a list of values e. g. a list of your enemies, a list the items you are currently carrying etc.. To define a variable to be a list you need to declare it to be a Lua table. Let’s declare the variable myEnemies as a list containing the names of your enemies:
myEnemies = {}
You can now add new enemies to this list by calling the Lua function table.insert( listName, item )
. For example:
table.insert( myEnemies, "Tom" )
table.insert( myEnemies, "Jim" )
To print the contents of your enemy list on the screen, you can run this script:
display( myEnemies )
Now, let’s make a little alias that adds a new name to your enemy list when you type "add enemy" followed by the name of the enemy (e.g., "add enemy Peter"). Open the alias editor by clicking on the "Aliases" icon. Click on the "Add Item" icon to add a new alias. Choose any name you like for your alias (e.g., "Add Enemy Alias"), and then define the following pattern for the alias: ^add enemy (.*)
. Next, add the following little script in the script input field below your alias:
table.insert( myEnemies, matches[2] )
echo( f"Added a new enemy:{ matches[2] }\n" )
Save the alias by clicking on "Save Item" and try it out by entering into the Mudlet's command input line. Aliases are explained in further detail below.
Another way to declare a list is to define its values directly. For example,
myEnemies = { "Peter", "Jim", "Carl", "John" }
To remove an item from the list, you can use the function table.remove( listName, item index )
.
Saving variables
You might notice that Mudlet doesn't save your variables between profiles restarts. The reasons for this are technical, but all it means is that you have flexibility in how to deal with them. There are several ways, so the most common and easiest ones will be explained here.
Tick the box in the variables view
Head to the variables view in the Mudlet editor and tick the box besides a variable - Mudlet will remember it between restarts now!
Saving by coding them in a script
The title sounds a bit complicated, but that's pretty much what you do. Go to Scripts, click `Add Item`, and create your variables like so:
myname = "Bob"
mypack = "pack1234"
rapierID = 67687
Now, since scripts are run when the profile is started, these variables will be created and assigned to those values. This was simple to do, but it has one problem - if you want to change the value of the variables to be saved, you have to edit the script by hand each time; and if you change the value of variables while playing via scripting, the new values won't be recorded.
Saving via table.save & table.load
Next, enter a more proper solution. This'll actually save the variables to a file and load them from it - so if you change the variable values, the current ones will be saved, and will be loaded next time properly. This method works with a table containing your variables though, not individual variables themselves - see Lua tables tutorial on how to create and use those.
table.save(where to save, what table to save)
takes the location and name of a file to save variables to, and a table containing your variables to save. Location can be anywhere on your computer, but a good default place is your profile folder, whose location can be obtained with getMudletHomeDir().
mychar = {
name = "Bob",
age = 26,
sex = "male"
}
local location = getMudletHomeDir() .. "/mychar.lua"
table.save(location, mychar)
-- sample echo to show where the file went:
echo(f"Variables saved in: '{location}'")
table.load(where to load from, what table to use)
is similar - it takes the location and name of the file to load, and a table name to use for the loaded variables.
mychar = mychar or {}
table.load(getMudletHomeDir() .. "/mychar.lua", mychar)
display(mychar)
echo(f"My name is: {tostring(mychar.name)}")
Now that you have a way to save and load your tables, you can create triggers to load and save your variables at appropriate times, and you'll be set.
React on input - Mudlets Alias Engine
Note: A screencast is available on getting started with aliases - watch it!
Mudlet has a feature called "aliases" that allows you to set up certain phrases or commands that will automatically trigger certain actions or responses. These actions are defined using a specific type of language called "Perl regex expressions." Aliases only work on the input that the user types into the command line, while a separate feature called "triggers" works on the output that the game sends back. When you type a command and press enter, it is sent to the alias feature to see if it matches any of the phrases or commands that have been set up. If it does match, the alias will take over and either send a different command to the game or run a script (a set of instructions) that you have defined. This system is powerful because it gives you control over what happens when a certain phrase or command is entered. You can even change the user's input as it is being processed, allowing you to manipulate the command before it is sent to the game.
The example in the diagram above shows 2 matching aliases, but only one of them sends commands to the game - and only if the player is healthy enough to attack the opponent. The other alias that matched the user input (enemy) choses a fitting opponent and sets the variable enemy accordingly, otherwise it issues a warning that attacking one of the available enemies would be too dangerous.
For an alias to match the command text the same rules as explained above in the trigger section apply. However, to simplify matters there is only one alias type. As alias are not performance critical we could reduce the amount of trigger types to just Perl regex as this type can do it all and performance is no issue with alias as the amount of data is much less. Even if you type like a madman you’ll never get close to sending the same amount of text to the game than the amount of text the game sends back to you.
What does it mean that a regex is true or "matched"? A trigger or an alias fires - or executes its commands/script - when the text matches the pattern of the trigger or alias. In most cases this means that the text contains the trigger/alias pattern. If the regex pattern is reen
then a text "The green house" will match because "reen" is contained in the text. More complex regex patterns can also hold information on where in the text a certain pattern must occur in order to match. ^tj
only matches when the letters "tj" occur at the beginning of the text. Consequently, a text like "go tj" would not match. Regex patterns can also capture data like numbers, sequences of letters, words etc. at certain positions in the text. This is very useful for game related scripting and this is why it is explained below.
Let’s get back to alias. We start with a simple example.
We want Mudlet to send "put weapon in bag" whenever we type "pwb". Consequently, the pattern is pwb
and as the task is so simple it’s enough to enter "put weapon in bag" in the send field. Then we click on save to save the changes and activate the alias by clicking on the padlock icon. Then we leave the trigger editor and test our new alias. After typing "pwb" and pressing return Mudlet will send the command "put weapon in bag" to the game.
Let’s move on to a more complicated example that is needed very often.
We want our script to automatically put the weapon in the correct bag as we have many bags and many weapons. The pattern stays the same. ^pwb The ^ at the beginning of the line means that the command starts with pwd and no other letter in front of this. If we define our pattern more clearly, the pattern will match less often. Without the ^ the alias will match and the alias script will always be run whenever there is the sequence of letters "pwb" in your commands. This may not always be what you want. This is why it’s usually a good idea to make the pattern definition as exact as needed by being less general. The more general the pattern, the more often it will match.
Back to our task: The pattern is ^pwb
. Let’s assume that we have defined 2 variables in some other script. The variable "weapon" is the weapon we use and the variable "bag" is the name of the bag. NOTE: In Mudlet global variables can be accessed anywhere from within Mudlet scripts - no matter if they have been defined in a trigger script, in an alias script or in a key or button script. As soon as it’s been defined it somewhere it is usable. To make sure that a variable is local only, i. e. cannot be referenced from other scripts, you have to use the keyword local in front of your variable definition. Back to our alias: Pattern is: ^pwb
Script is:
send(f"put {weapon} in {bag}")
Depending on the values of our variables weapon and bag the command "pwb" will be substituted with an appropriate command. To set your weapon and bag variables we use 2 more aliases: Alias to set the weapon: uw (\w)+
Script:
weapon = matches[2]
send( "wield " .. weapon )
To set our bag variable: Pattern:^set bag (.*)
bag = matches[2]
Now let’s go back to our initial problem. We want an alias to put our current weapon into our current bag. But what happens if we are in the middle of a fight and absolutely need to sip a healing potions because we are close to death and cannot take the risk that the bag may be too full to take the weapon? We want to upgrade out little alias to take into account that the bag may be full and chose an empty bag instead. To do this we set up a trigger that detects messages that indicate that the attempt to put the weapon in the bag failed. In this trigger we execute this little bag-is-full-detection-trigger Trigger Pattern: (type substring) Your bag is full.
Script:
bagIsFull = true;
This detection trigger will set the variable bagIsFull
to true as soon as it sees the message "Your bag is full.". Then you know that you have to use your spare bag to take the weapon.
Now we have the tools to write an improved version of our little alias script:
if bagIsFull then
send(f"put {weapon} in {spareBag}")
else
send(f"put {weapon} in {bag}")
end
The next example is one of the most common aliases a tell alias: Pattern:^tj (.*)
Script:
send("tell Jane " .. matches[2])
Sadly, Jane is your fiancée and the one thing she is a vegetarian and absolutely hates all words that relate to meat. Luckily, you know enough about aliases by now to make her believe that you’d never ever even think about meat. So you head to your global function script (any script item will do as long as you define your variables outside of your function definitions. See the scripts chapter below for more information. In your script "my global functions" you add a Lua table containing a list of all of all words that a vegetarian might hate. For example:
happyJaneTable = {"meat", "burger", "steak", "hamburger", "chickenburger"}
Now you can upgrade your tell-jane script to automatically search our tell for all words that Jane might not like. In case such a word is found we substitute the entire tell with "How is the weather?".
for key, value in ipairs(happyJaneTable) do -- looking at each element of the list
badWord = happyJaneTable[key] -- check out the Lua table chapter below for more info
begin, end = string.find(command, badWord) -- begin holds the start position of the word, end* the end-position
if begin ~= nil then -- we have found a bad word
send("tell Jane How is the weather?")
return
end
end
Default keybindings in the main window
Keypress | Action |
Left Arrow | Moves the cursor one character to the left. |
Shift+Left Arrow | Moves and selects text one character to the left. |
Right Arrow | Moves the cursor one character to the right. |
Shift+Right Arrow | Moves and selects text one character to the right. |
Home | Moves the cursor to the beginning of the line. |
End | Moves the cursor to the end of the line. |
Backspace | Deletes the character to the left of the cursor. |
Ctrl+Backspace | Deletes the word to the left of the cursor. |
Delete | Deletes the character to the right of the cursor. |
Ctrl+Delete | Deletes the word to the right of the cursor. |
Ctrl+A | Select all. |
Ctrl+C | Copies the selected text to the clipboard. |
Ctrl+Insert | Copies the selected text to the clipboard. |
Ctrl+K | Deletes to the end of the line. |
Ctrl+V | Pastes the clipboard text into line edit. |
Shift+Insert | Pastes the clipboard text into line edit. |
Ctrl+X | Deletes the selected text and copies it to the clipboard. |
Shift+Delete | Deletes the selected text and copies it to the clipboard. |
Ctrl+Z | Undoes the last operation. |
Ctrl+Y | Redoes the last undone operation. |
Ctrl+<Click> | Select the whole line. |
Ctrl+Enter | Close split screen (scroll all the way to the bottom). |
Ctrl+F | Search for text in the main output window. |
Trigger Engine
Unlike alias that define patterns that match on user input, triggers define patterns that match on game output. In other words, triggers react to text that has been sent by the game, whereas alias react to user commands that have been typed into the command line.
Simple Trigger Matching
Note: QUICKSTART: Here is a simple video tutorial on how to make basic triggers in Mudlet.
To begin with, click on the "Add" button to create a new trigger. Then put the text pattern that you’d like to trigger on into the trigger conditions table on the right side of the screen above the script editor. Afterwards, chose the correct pattern type of your trigger pattern in the drop down list on the right side of the trigger pattern i.e. in the second column of the trigger pattern table. If you define multiple patterns in the same trigger, your trigger will run whenever any one of these patterns matches unless you chose the AND-trigger option, in which case the trigger will only fire if all patterns match within a specified amount of lines from the game. For more advanced information on AND and OR trigger see the corresponding AND/OR trigger section below. The next step is to define what should happen when the trigger matches. Usually, this will be done by a Lua script in the Lua editor below the table with the pattern list. In the beginning, you can simply chose the "highlight trigger" option to make your trigger highlight the text that it has triggered on or send a clear text command to the game whenever the trigger fires until you have learned enough Lua to more meaningful scripts. Clear text command can be defined in the "send plain text" input box next to the trigger name above the pattern table. Finally, you need to save the new trigger and then activate it with the padlock icon button. By default, new triggers are deactivated and thus will do nothing unless you explicitly activate them. Activated triggers show a green tick in the little blue box on the left side of the trigger name in the trigger tree on the left side of the script editor dialog. There is three ways to save your changes. 1. click on the save icon 2. adding a new trigger 3. clicking on another trigger item. Triggers that have not been saved yet cannot be activated. If you see a bug icon instead of an activation box, there is some error that prevents to activate your trigger. Check the error message above the pattern table.
Example: You want to trigger on the word "pond" in a line such as: "The frog swims in the pond. Plop." All you need to do is add "pond" as a pattern and chose "substring" as a pattern type. Then enter the command you like to send to the game if the trigger matches. For example enter "drink water" into the "send plain text" input box and activate your new trigger. Your new trigger will send the command "drink water" to the game any time it sees the word "pond" somewhere in the game output.
Simple Highlighter Triggers
Note: Beginners should use Mudlets automated highlight triggers in the beginning to get the hang of the different trigger and pattern types quicker. Click on the "highlight trigger" option and pick a foreground and a background color. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. This helps you spot things at a single glance instead of reading the entire text. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.
More advanced users will often want to do custom highlighting from within scripts. This is how it works: If you want to highlight the word "pond" in the above example you have to add the following little Lua script to the script editor on the lower right side of the Script Editor window:
selectString( "pond", 1 )
fg( "red" )
bg( "blue" )
resetFormat()
"multiline / AND" and "OR" Condition Triggers
Multiline, or AND triggers execute their respective command or script only if all conditions in their respective conditions expression list are fulfilled.
OR-Triggers execute when any one of their conditions is true. To make OR-Triggers you simply have to add a few conditions to the conditions list e.g. in our example: "pond", "frog", "Plop". The trigger will now also execute on lines like this: "A frog is green" or "You hear a loud Plop!" because "frog" matched in the first line and "Plop" matched in the second line.
Multiline / AND triggers execute when all of their conditions are true. Taking the previous patterns of "pond", "frog", "Plop" and clicking the 'AND' button will make the trigger not fire on "A frog is green" or "You hear a loud Plop!" anymore, because all 3 patterns don't match. It however would fire on "In a brown pond, the frog said Plop!" because all 3 patterns matched. As you might have noticed, all 3 patterns are on the same line: this means that in a multiline/AND trigger, the next pattern starts matching on the same line to make this work.
To make the engine skip lines in a multiline / AND trigger, use the line spacer pattern: select 'line spacer' as the type and put in a number on the left to make it go to the next X lines, for example 1 will make it go to the next line.
The simplest form of AND-Triggers in Mudlet are Trigger Chains or Filter Chains, whatever you’d like to call it.
Trigger Chains & Filter Chains
"Chains" and "filters" are different trigger group entities in Mudlet and serve completely different ends.
Chains
A chain is defined in Mudlet by making a trigger group and adding a trigger pattern to the group. A group without a pattern is a simple trigger group that serves no other purposes than adding structure to your trigger system in order to organize your triggers better. Such a normal trigger group will always grant access to its children unless it has been explicitly disabled (= all access to itself or any of its children is locked) either manually or by a script.
A trigger group with a defined trigger pattern, however, will behave like a normal trigger and match if the pattern matches. Such a trigger group is called "chain head". A chain head will only grant access to its children if the trigger pattern has matched and the chain has been enabled. Thus, chains can be looked at as a mechanism to automatically enable and disable triggers or groups of triggers when a certain condition has been met i. e. the trigger pattern of the chain head has been matched. (However, technically this is not correct as disabled child triggers will not be invoked if the chain head matches. In other words, in chains you can still have enabled/disabled elements. The idea of a chain can better be described by necessary and sufficient condition - both of which need to be met before a child trigger is being run.)
Adding child triggers to this group will add elements to the trigger chain. These chain elements will only be activated if the chain head has matched before and thus opened the trigger chain. The chain stays open until the "keep chain open for x lines" value has been reached. The default is 0 which means that the chain only stays open for the current line. When access to the chain has been granted all child triggers will be tested against the content of the current line. Consequently, trigger chains are a means to automatically enable/disable trigger groups without the hassle of enabling and disabling trigger groups manually. This has 2 important advantages: Chains are faster than conventional solutions and chains reduce the complexity of your scripts and greatly reduce the usual system bugs that inevitably go along with enable/disable trigger xy function calls as it’s very difficult and error prone to enable and disable your triggers correctly in large complex trigger systems. This is one of the most powerful features in Mudlet and should be used whenever possible.
Let’s look at a practical example for a trigger chain:
My newbie prompt on Achaea looks like this 500h, 500m ex-
when I have balance and 500h, 500m e-
when I have lost balance. We are going to develop a prompt detection trigger that raises the event gotPrompt and sets the variables myBalance=true
or myBalance=false
To begin with, we add a new trigger group and add the Perl regex pattern to detect the prompt:
^(\d+)h, (\d+)m
The pattern reads in plain English: At the beginning of a prompt line there are is a number directly followed by the letter h, a comma, a space and another number followed by the letter h. Whenever this pattern matches the trigger will fire and we’ll know that we have a prompt line. We use the 2 numbers that we captured in our pattern to update our health and mana stats.
Detecting balance is more difficult as balance is indicated by the letters ex- on the same line after the prompt and imbalance is indicated by the letters e-. As we have set a pattern in a trigger group (folder), the folder is turned into a trigger chain head. It will now only let data through to its children when its own pattern is matched. In other words, the child triggers of the trigger chain will only receive data on prompt lines. We are going to take advantage of this by adding two simple substring triggers to detect balance and imbalance. The balance trigger pattern is ex- and the imbalance detector pattern is e-.
In the two balance detection triggers we now write myBalance=false
and myBalance=true
respectively plus a little echo on the screen that shows our current balance status.
We could now add a call deleteLine()
to the prompt detection trigger to erase the prompt from the screen if we don’t want to see it as we have computed all relevant information.
Filters
You can turn a trigger chain head into a filter by checking the "only pass matches" option. This changes the content of what is forwarded as trigger text to the children triggers in the chain. Chains forward the content of the current line as trigger text whereas filters forward the matched pattern instead of the current line. In other words, the text of the current line is filtered according to the pattern of the filter. For example: You want to know the exits in the current room. The simplest solution is a simple filter on You see exits to: (.*)
Then you simply add triggers to the filter chain such as north
, south
, west
, east
etc. The direction triggers will only be called if the filter head has matched.
Imagine the following scenario: You want to collect some berries. You know that the room contains some berries if the room description contains the words "You are inside a forest. There are some strawberries." or "You are inside a forest. There are some blackberries." and there are always only one kind of berry in the room. You make a new substring trigger for this line, but instead of choosing a regular trigger, you chose to add a new trigger group. Now you add You are inside a forest\. There are some (\w+)\.
as an Regular Expression to the expression list of the trigger group. When adding conditions to a trigger group, the trigger group turns from an organizational unit into a filter unit, if the "filter" option is checked. From now on this folder is a filter and will only let its matches pass through. In our case this is exactly what we want, because we don’t want to collect all sorts of berries, but we only want 2 particular kinds, namely, strawberries and blackberries, and we know that these berries can only be trusted if they are picked inside a forest as other areas may contain contaminated berries. Now you add two regular triggers to our berry-in-the-forest filter - one containing the condition: strawberries
and the other one blackberries
. Then we add the commands to pick the particular kind of berry to both triggers (send field). Now what happens is that as soon as a room description reads "You are inside a forest. There are some strawberries/blackberries." the filter will let the kind of berry pass through to our two berry triggers and they will issue commands to pick berries, if there are such berries. However, in any other situation the words "strawberries" and "blackberries" will NOT trigger a pick - only in the above scenario when the filter parent’s condition is met. This is a very nice way to solve complicated problems with a few easy filter chains. This example is trivial, but using filter chains will rapidly show you how formerly complicated things that could only be solved with very complicated regular expressions can be solved easily now with a couple of filter chains.
Multi-Line Triggers and Multi-Condition Triggers
Multi Condition Triggers are the most advanced feature of Mudlets trigger engine. Like trigger chains or filter chains they are a form of AND-Triggers. All conditions in the list must have matched within the specified margin of lines (delta), in order to trigger the script. Normal triggers fire and run the script as soon as one of the conditions in the regex list is met i.e. if one of the regex/string matches match - or the Lua function condition returns true, the trigger script is run. In multiline triggers, however, each single regex/string/Lua function condition in the list has to have matched within the specified margin of lines at least once to trigger the script. The sequence of the conditions is binding. This means that if the 10th regex on the regex list would be matched on the eleventh line after the match of the first line happened, the trigger will NOT run unless the margin of lines is set to 11. If condition #3 is true but currently #2 is waiting to be true, condition #3 is ignored and must be true again after condition #2 has been true. Conditions can also be Lua Functions or plain Lua code that returns a boolean truth value. You can mix all types of conditions to build complex multi-condition triggers that only fire if all conditions are met. This is a very powerful feature as it reduces the amount of scripting to a minimum or even takes away with the need to script formerly complex processes completely. Multicondition triggers are multi-line triggers, i. e. the conditions can all be met in a single line or many lines after the first condition has been fulfilled. This effectively reduces the amount of complexity as you have all the important conditions placed into a single trigger and all the tedious bookkeeping, variable and condition state accounting is being done by Mudlets trigger engine. The result of this is that the amount of manual condition checking via many different trigger scripts and legions of if condition1 == true then check condition2 can be forgotten about. All you have to do is to define the conditions and the final action that is taken if the trigger fires.
Note: to retrieve wildcards in multi-line or multi-condition triggers, use the multimatches[line][match] table instead of matches[].
Note: This diagram shows what steps are involved in the process of problem solving with Mudlets trigger engine. The main question is: How do we arrive at a solution to our problem, and how can we simplify the problem as much as possible?
Example: Let’s go back to our pond & frog example. We have explained the difference between AND-triggers and OR-triggers. If you have a room description consisting of 3 lines:
- You see a pond
- You see a frog.
- The frog sits on a stone.
Every single one of these 3 lines will be fed into the trigger engine one after another. If we define an OR-trigger with a condition list consisting of 3 condition patterns:
- condition #1 pattern = pond
- condition #2 pattern = frog
- condition #3 pattern = stone
Whether or not a condition is found to be true also depends on another property, namely the type of the condition. The condition type can be among others:
- substring matching → the condition is true if the condition pattern is a substring of the output line from the game. In other words: If the pattern "pond" is contained in any line of output, the condition is true.
- begin of line matching → the condition is only true if the condition pattern can be found at the beginning of a line from the game.
- Perl regular expression → the condition is true if the Perl regex pattern is matched. You’ll find more information on Perl regex below.
- Lua code that returns a truth value e.g. a call to a function check() that return either true or false depending on the condition
In our example we chose condition type "substring" for all three conditions. Consequently, the trigger will fire the command or script 3 times i. e. the trigger will do on each line it is matched against because in every line at least one condition evaluates to true because the pattern is a substring of the line.
- in line #1 we get: pond = true.
- in line #2 we get frog = true and
- in line #3 two conditions are true i.e. frog=true and stone = true
Because an OR-trigger fires on the first condition that is true and ignores the rest the trigger will only execute 3 times on these 3 lines although 4 conditions are true.
Note: CAUTION: The multi line condition switch must be turned off to get an OR-trigger! If the multi-line condition switch is turned on the trigger becomes an AND trigger which means that the trigger only fires if all conditions are true and fulfilled in the correct sequence. With OR-triggers the sequence is irrelevant.
To complicate matters, however, you don’t want your trigger to fire 3 commands, because you want to use this room description as a whole to fire your trigger e. g. this pond is the only kind of ponds in the entire world that doesn’t have poisoned water. So you want to make sure that you only drink water from a pond of this kind and from no other pond. Your solution is to use Multi Condition Triggers (MCT). If you check the MCT checkbox this trigger will fire only once from now on - and only if all conditions are met i e. when you can guarantee that you only drink water from a good pond because your drinking trigger is matching on the entire room description despite that this room description my be spread over a number of lines. (NOTE: If you have word wrap turned off in your game chances are that the entire room description will be contained in a single line, but we are trying to keep the examples as easy as possible.)
Sadly, there are many unfriendly people in this world and somebody goes around and poisons your good ponds. Consequently, you would want to examine the frog and find out if it is poisoned before drinking water from the pond. This is difficult because the villain is a mean magician who used illusion spells to make everything look like the good pond. To solve the problem you can now resort to Lua function conditions in the trigger condition list that perform certain check ups to put the current room description into a wider context e. g. check if you have been here before etc. This adds yet another level of complexity to your problem but this is a very powerful means to use the full potential of Mudlets MCTs.
You can combine all forms of conditions with trigger chains, filters and Lua functions. Mudlet gives you relatively easy to use tools that require no programming background. However, these tools can evolve into complex powerful problem solving mechanisms if they are combined with each other thus enabling non-programmer users to solve problems that would need a profound programming background in other gameclients. However, unlocking the full potential of Mudlet requires you do learn some Lua basics. In this manual we’ll try to be as easy on you as we can in this respect, but it’s highly recommended that you dig deeper into Lua after a while. It’s one of the easiest fully fledged scripting languages available, easy to learn and the fastest of them all, and this is why it has been chosen by us. You don’t need to become a programmer to be able to use Mudlet effectively. All you have to know is how to work with variables and how to do if conditions and maybe a few loops. But knowing more won’t harm you and it will make your systems more effective.
Named capturing groups in Perl regex triggers and tempRegexTrigger
Since Mudlet 4.11+ you can use named capturing groups in , so you can access your matches not only by numeric index of your capturing group but also under certain name. It is especially useful when you have multiple patterns with different ordering of capture groups.
Let's assume we want to capture name and class of character, but MUD outputs it two ways.
My name is Dargoth. My class is a warrior.
I am a wizard and my name is Delwing.
Instead of creating two different triggers we can create only one containing alternative matching patterns:
^My name is (?<name>\w+)\. My class is a (?<class>\w+)\.
^I am a (?<class>\w+)\ and my name is (?<name>\w+)\.
Notice that class and name come in different order, therefore in first case we will have name under matches[2] and in second case under matches[3]. With named capture groups in both cases we will have name available under matches.name and class under matches.class.
Code example to handle named matches above:
echo("Name: " .. matches.name .. "\n")
echo("Class: " .. matches.class .. "\n")
To verify whether named groups are available you can use flag mudlet.supports.namedGroups
.
Lua Code Conditions & Variable Triggers - Expression Triggers
If you set a trigger type to 'lua function', you can run Lua code inside the trigger engine directly, as a trigger pattern. If the trigger pattern returns true, then the pattern will be considered to have matched, and corresponding trigger code will run.
As an example, lets make a variable trigger: add a new trigger and choose pattern type lua function. Then define this pattern: if health <= 100 then escape() end
. If your health is lower than 100, and your escape function with more logic inside it returns true, the pattern will match. Another formulation of the same would be: checkHealth()
. For the last formulation to work you have defined a Lua function checkHealth()
. Open the script editor, add a new script "health care" and add this code to the new script-script.
function checkHealth()
if health <= 100 then
echo( "WARNING: Low health! I have to run away!\n" )
startEscape()
return true
else
return false
end
end
Note: Mudlet used to only allow the boolean true value as the return value to consider the pattern to have been a match. It has since been improved to allow any value Lua would consider true - but if you see any LFCs making use of and true or false at the end, that'd be why.
Lua Syntax Primer: Expressions
if A == B then (...) ----> if A equals B
if A ~= B then (...) ----> if A *NOT* equals B
if A <= B then (...) ----> if A is smaller or equal to B
if A >= B then (...) ----> if A is greater or equal to B
if A < B then (...) ----> if A is smaller than B
if A > B then (...) ----> if A is greater than B
The operators and and or behave differently in Lua than in most other programming languages as they are not guaranteed to return a boolean value.[1]
Lua function conditions effectively means that you run the Lua code they represent on every single line that is received from the game, unless the LFCs are part of a multi-condition trigger, in which case the LFCs would only be run when they would be the current test-condition of their respective trigger state. LFCs are implemented in such a way that the trigger engine only calls the compiled byte code, but running as few scripts as possible is always the best idea. LFCs are nice and handy, and for most people the performance aspect will not be relevant at all.
Testing triggers
You can test your triggers with the `echo alias from the command line:
`echo A test line.
`echo One line.$Next line.$Third line.
Alternatively, you can also record a replay and play it - triggers will be matched on it.
Named patterns
You can use named patterns - that is, giving your captures names instead of [2], [3], [4] numbers - by adding ?<variablename> to your capture in Mudlet 4.11+:
-- before:
(\w+) = matches[2]
-- now:
(?<name>\w+) = matches.name or matches["name"]
(?<weapon>\w+) = matches.weapon or matches["weapon"]
This can be particularly handy if you have several patterns in a trigger and the location of matches[n] moves around. Try this out in a demo package.
Named capture groups still will be available under their respective number in matches
.
You can programatically check if your Mudlet supports this feature with mudlet.supports.namedPatterns
.
Editor
Editor shortcuts
The following shortcuts are available in the Lua code editor:
Navigation shortcuts | |
---|---|
Ctrl+Tab | Focus next section |
Ctrl+Shift+Tab | Focus previous section |
Ctrl+S | Save current item (trigger, alias, etc.) |
Ctrl+Shift+S | Save complete profile |
Ctrl+1 | Show trigger editor |
Ctrl+2 | Show aliases editor |
Ctrl+3 | Show scripts editor |
Ctrl+4 | Show timers editor |
Ctrl+5 | Show keys editor |
Ctrl+6 | Show variables editor |
Ctrl+7 | Show buttons editor |
Ctrl+8 | Show error log console |
Ctrl+9 | Display statistics in main window |
Ctrl+0 | Open central debug console window |
Selection shortcuts | |
---|---|
Ctrl+A | Select all text |
Ctrl+Left click | Add cursors |
Ctrl+Alt+Up | Extend custors up |
Ctrl+Alt+Down | Extend custors down |
Esc | Switch to one cursor |
Ctrl+D | Select words at the cursor |
Ctrl+L | Select next lines |
Ctrl+Shift+L | Select previous lines |
Ctrl+F | Opens the script editor's FIND dialog. |
F3 | Moves to the next FIND result. |
Shift+F3 | Moves to the previous FIND result. |
Editing shortcuts | |
---|---|
Ctrl+] | Indent right |
Ctrl+[ | Indent left |
Ctrl+Shift+D | Duplicate |
Ctrl+/ | Toggle selection comment |
Alt+Backspace | Delete rest of the word left |
Ctrl+Backspace | |
Shift+Backspace | |
Alt+Delete | Delete rest of the word right |
Ctrl+Delete | |
Shift+Delete | |
Ctrl+R | Toggle read-only |
Unicode
Reference our manual page on Encoding for more information on CHARSET negotiation in Mudlet.
Changing encoding
Mudlet is being developed to support displaying text in many languages but how the characters that conveys that language varies between games as does the languages they support. Plain vanilla Telnet actually only supports the 96-characters of ASCII by default, but other language can be supported if the way that they are converted into 8-bit bytes can be agreed upon by the use of what is called encoding - setting Mudlet (and the game server if approriate) to the correct encoding allows the correct display of characters like the Spanish ñ, the Russian я, and all other letters (or more properly grapheme).
Go to Preferences > General to set the encoding:
The list of encodings supported by Mudlet is:
Encoding | Mudlet version |
---|---|
ASCII | 0.0.1 |
UTF-8 | 3.2.0 |
ISO 8859-1 | 0.0.1 |
CP850 | 3.2.0 |
CP866 | 3.2.0 |
CP874 | 3.2.0 |
ISO 8859-10 | 3.2.0 |
ISO 8859-11 | 3.2.0 |
ISO 8859-13 | 3.2.0 |
ISO 8859-14 | 3.2.0 |
ISO 8859-15 | 3.2.0 |
ISO 8859-16 | 3.2.0 |
ISO 8859-2 | 3.2.0 |
ISO 8859-3 | 3.2.0 |
ISO 8859-4 | 3.2.0 |
ISO 8859-5 | 3.2.0 |
ISO 8859-6 | 3.2.0 |
ISO 8859-7 | 3.2.0 |
ISO 8859-8 | 3.2.0 |
ISO 8859-9 | 3.2.0 |
KOI8-R | 3.2.0 |
KOI8-U | 3.2.0 |
MACINTOSH | 3.2.0 |
WINDOWS-1250 | 3.2.0 |
WINDOWS-1251 | 3.2.0 |
WINDOWS-1252 | 3.2.0 |
WINDOWS-1253 | 3.2.0 |
WINDOWS-1254 | 3.2.0 |
WINDOWS-1255 | 3.2.0 |
WINDOWS-1256 | 3.2.0 |
WINDOWS-1257 | 3.2.0 |
WINDOWS-1258 | 3.2.0 |
Scripting with Unicode
Mudlet uses English in all of its Lua API to enable scripts scripts to be international - so a script written on a computer with German default will work on a computer with English default, for example. This means you can expect all API functions, error messages to be in English, and the number separator is always a period .
Mudlet sets os.setlocale("C")
by default, see background.
Not all Lua functions beginning with string.
will work with Unicode - Mudlet has utf8.
equivalents for those. See String functions in Mudlet for a complete list. For example:
print(string.len("слово"))
> 10 -- wrong!
print(utf8.len("слово"))
> 5 -- correct!
Triggering with Unicode
Mudlet's trigger engine fully supports Unicode in all types of patterns, including regex.
Loading external Lua files
Mudlet uses Unicode (utf8) for the trigger engine and Lua subsystem. If you have a file you're loading externally with Lua, make sure it saved in utf8 encoding.
Timer Engine
Mudlet supports 3 different sorts of timers:
- Regular GUI Timers
- Temporary Timers
- Offset Timers
The first can be configured by clicking and will start some code in regular intervals. The second and third can be used in other scripts you code. All of them are described in more detail below.
Regular GUI Timers
Regular GUI Timers that fire repeatedly in a certain interval specified by the user. To make one, go to the Timers section (1) in Mudlet, click Add (2), select the time periods you'd like the timer to be going off at - save (3) and activate it (4). The timer will go off after your specified interval and then at regular specified intervals after that, until disabled.
You can also enable/disable this timer via scripting with enableTimer() and disableTimer():
enableTimer("Newbie timer") -- enables the timer, so 2s after being enabled, it'll tick - and every 2s after that
disableTimer("Newbie timer") -- disables it, so it won't go off anymore
Temporary Timers
Temporary Timers are timers that go off only once and are the most common type of timer used for scripting purposes. You don't work with them from the Timers section - you just code with them only.
For a basic introduction to temporary timers, read up about them here. Here, we'll continue expanding on what you've learnt so far.
One thing to keep in mind when working with tempTimers is that they are unlike #wait statements you might see in other clients. While #waits are typically cumulative, tempTimers aren't - they go off from the same point in time. Thus if you'd like two timers to go off - one after 3s, and another 1s after the first one - you'd set the second timer to go off at 4s. For example:
tempTimer(3, [[ echo("this is timer #1 going off 3s after being made\n") ]])
tempTimer(4, [[ echo("this is timer #2 going off 4s after being made - and 1s after the first one\n") ]])
Note: Temporary timers cannot be accessed from the GUI and are not saved in profiles.
Stopping
To stop a temporary timer once you've made it and before before it went off - you use killTimer(). You give killTimer(id) the ID of the timer that you've made - which you get from Mudlet when you make it. Here's an example:
-- get and store the timer ID in the global "greeting_timer_id" variable
greeting_timer_id = tempTimer(2, [[ echo("hello!\n") ]])
-- delete the timer - thus nothing will actually happen!
killTimer(greeting_timer_id)
Refreshing
You can also use killTimer() to "refresh" a timer - the following code example will delete the previous timer if one exists and create the new one, thus making sure you don't get multiple copies of it:
if portal_timer then killTimer(portal_timer) end
portal_timer = tempTimer(2, [[ send("enter portal") ]])
Using variables
To embed a value of a variable in tempTimer code, you might try using this given what you've learnt:
tempTimer(1.4, [[ echo("hello, "..matches[2].."!\n") ]])
But that won't work as you'd expect it to - that will try and use the value of matches[2] when the timer goes off - while by then, the variable could have changed! Instead, you take it outside the square [[ ]] brackets - this is correct:
tempTimer(1.4, [[ echo("hello, ]]..matches[2]..[[!\n") ]])
-- or with less brackets:
tempTimer(1.4, function() echo("hello, "..matches[2].."!\n") end)
Nesting
If you'd like, you can also nest tempTimers one inside another - though the first [[]]'s will become [=[ ]=]:
tempTimer(1, [=[
echo("this is timer #1 reporting, 1s after being made!\n")
tempTimer(1, [[
echo("this is timer #2 reporting, 1s after the first one and 2s after the start\n")
]])
]=])
If you'd like to nest more of them, you'd increase the amount of ='s on the outside:
tempTimer(1, [==[
echo("this is timer #1 reporting, 1s after being made!\n")
tempTimer(1, [=[
echo("this is timer #2 reporting, 1s after the first one and 2s after the start\n")
tempTimer(1, [[
echo("this is timer #2 reporting, 1s after the second one, 2s after the first one, 3s after the start\n")
]])
]=])
]==])
Closures
Last but not least, you can also use closures with tempTimer - using a slightly different syntax that has advantages. For example, you have access variables in its scope, when it goes off:
local name = matches[2]
tempTimer(2.4, function() echo("hello, "..name.."!\n") end)
Also syntax highlighting will work as expected, because the function will not be given as a string.
Note: In this case, you mustn't use matches[2] directly in the echo() command. It will not work as expected. Instead, bind the it to a new variable like name as seen in the example above.
Offset Timers
Offset Timers are child timers of a parent timer and fire a single shot after a specified timeout after their parent fired its respective timeout. This interval is an offset to the interval of its parent timer. To make them, add a regular GUI timer (see above), then create another timer and drag it onto the timer. This will make the timer that is "inside" the timer (the child inside the parent) go off at a certain time after its parent goes off. Offset timers differ visually from regular timers and are represented with a + icon for offset. Offset timers can be turned on and off by the user just like any other timer. For example - a parent timer fires every 30 seconds and by doing so kicks off 3 offset timers with an offset of 5 seconds each. Consequently, the 3 children fire 5 seconds after each time the parent timer fired. To make this happen, make the parent timer tic every 30 seconds, drag 3 timers into it with an offset of 5s on each:
Uses and examples
Enable/disable triggers
This'll make use of tempTimer to enable a trigger and disable it after a short period of time:
enableTrigger("Get enemy list")
tempTimer(3, [[disableTrigger("Get enemy list")]])
Running a script after the current triggers
A useful trick to get your code to run right after all of the current triggers (GUI and temporary) ran would be to use a time of 0:
-- in a script, this will run after all scripts were loaded - including the system, wherever in the order it is.
tempTimer(0, function()
print("this timer is running after all triggers have run")
end)
Have more examples you'd like to see? Please add or request them!
Mapper
Mudlet's mapper is split into two parts for the best compatibility on all games:
- The display of the map itself and functions to modify the map in Mudlet, and
- A very game-specific Lua script to track where you are, and provide aliases for using the mapper, automatic mapping, etc.
If your game does not provide a mapping script for you, then you may not see a map at first.
Fear not! Pre-made mapping scripts for many games are available from Mudlet forums - all topics that have the "mapping script"-prefix on them.
If you still don't find any, or if you want to create your own mapping script, see #Making your own mapping script further down below. Remember, you can always find help in Mudlet forums or Discord, etc.
Visual Map Editor
Maps can be comfortably edited by using the visual map editor or by scripts. The editor behaves like the usual WYSIWYG editors. Select objects with a left click and then right click to open a context menus and do actions on the selected objects.

The mapper starts in "view-only" mode to prevent accidental edits. The editing mode can be toggled in the map's right-click menu.
Object selection
- left click = select element
- left click + drag = sizing group selection box choosing all rooms in the box on the current z-level
- left click + shift + drag = sizing group selection box choosing all rooms in the box on all z-levels
- left click + alt (or the mapper menu move map buttons) = move map
- left click + control = add a room to current group selection or remove it
If multiple rooms are being selected, a room id selection list box is being shown where you can fine tune the current room selection via the usual left click + control or left click + shift. The box disappears if the number of rooms in group selection is zero.
Moving Objects
Move selected objects either by right click and select "move" or with following handy short cut:
- left button down on custom line point + drag = move custom line point
- left button down + drag usually moves the item directly (as a handy shortcut) if only one element has been selected
- or hold left button down + control + drag if multiple rooms have been selected
Maps and Autowalking
Maps are implemented as directed graphs of connected nodes (rooms). Nodes are connected by edges (exits). Nodes are referenced by unique integer IDs. Edges fall into 2 categories: Standard exits with a visual representation on the map (e. g. north, south) and "special exits" without a calculated visual representation on the map e. g. the command "jump cliff" is a special exit that connects to a room without a clear spatial orientation. However, special exits can be visually represented if the user provides custom exit line strips. Standard exits are referenced by their respective node and a directional integer value. Special exits are referenced by their respective nodes and strings that hold the exit commands. Both nodes and individual exits can seperately be locked and thus excluded from speed walk path finding graphs. Path finding uses the fast A* search algorithm. Mudlet choses a path with the fastest travel time (-> room weights) as opposed to the shortest path.
Maps are divided into areas or zones where the area/room relationship is unique, i. e. rooms cannot be in more than 1 area.
Note: Areas help make do with the typical geographical irregularities of game maps where an entire city with hundrets of rooms makes up a single room on a wilderness map. In other words, if you can't make a place look geographically correctly, create (sub) areas to deal with the problem.
There are 2 forms of visual representations of maps. Standard mode shows exits and custom exit lines whereas "grid mode" hides exit details and sizes rooms to form a perfect grid without any empty space in between rooms. Grid maps can be made to look exactly like ASCII color text maps with character symbols to keep the look and feel of the game. Technically, grid maps are a special optimized representation of the typically very large LPC MUD style wilderness maps where every room has 8 direct neighbors in a n*m grid of rooms with relatively few holes. The grid map implementation uses pre image caching and fast gfx hardware render support and can thus render very large grid maps in less than 1ms that would take much longer if the map were to be displayed in regular mode. Changing the zoom level of maps in grid mode can take a significant amount of time if the maps are very large, because the pre cached images of the map need to be recreated at the new zoom level. Areas remember their particular zoom level so this is no hindering issue in actual gameplay.
Any map can be displayed in both modes, though the visual map editor only works in regular mode. To enable area mode, use the setGridMode() function.
Regular mode:
Grid mode:
Areas
Areas are defined by a unique integer number ID and a unique area name. Mudlet builds an internal numerical area ID table on the basis of the rooms that belong to the respective areas. Mudlet keeps a seperate lookup table to retrieve the area name on the basis of the area IDs. This name lookup table is not guaranteed to be correct because it may be imported invalid information if the map has been downloaded by the game server as an xml map description file on the basis of the MMP protocol. [1] However, if the map has been created with Mudlet directly, there will be no such problems as the area name lookup table API is made to enforce uniqueness.
Area Properties
- area map display mode (-> regular map display mode or grid mode)
- area name
Rooms
Rooms are invisible on the map unless the required properties have been set.
Room Properties
- Room object need following required properties in order to be shown on the respective area map:
- unique room ID in form of an integer value
- area ID in form of an integer value (To which area does this room belong - or in other words, which area map displays this room)
- x, y and z coordinates as integer values which relate to its paricular area map coordinate system
- Optional room properties:
- regular exits with or without respective exit locks
- special exits with or without respecitve special exit locks
- room lock
- exit stubs (draw exit directions even though the exit rooms have not yet been defined)
- custom exit lines (user defined line strips of various formats to visualize special exits or redefine regular exit lines)
- searchable room name that can be used for bookmarks, annotations etc.
- room weight (How long does it travel through this node. A high room weight makes it less likely that this room will be chosen for pathfinding e. g. a safe road should have a low weight, whereas a dangerous place should have a high weight
- room color
- room character e. g. the symbol $ to symbolize a bank or H for a hotel.
Advanced map features
Map labels
Maps can be embellished with images and text labels. Map labels can be either used as background (default) or as the top most foreground e. g. for player name location scripts. Labels are defined by position and size according to the map coordinate system and keep their position and size relative to the rest of the map when the map is zoomed or moved. Contrary to rooms which work on the basis of integer (natural numbers) coordinates, labels are described (with respect to both position & size) by real numbers in order to allow for more advanced placement and label sizes within the map coordinate system. Map labels are stored in form of png images directly in the map file and are thus a direct part of the map. As these images are being scaled to fit the label creation size, the image quality will depend on the initial size of the label (the large the better the quality, but the more memory will be used).
(The desert and dragon images used in this example are licensed under the Creative Commons Attribution 2.0 Generic license and can be found here: http://en.wikipedia.org/wiki/File:Ninedragonwallpic1.jpg and http://en.wikipedia.org/wiki/File:Siwa_sand_dunes2009a.jpg)
Custom exit line definitions
The mapper supports user defined visual exit lines on the basis of a sequence of line points in the map coordinate system. Custom lines as well as labels work on real numbers to allow for fine grained placement. User defined lines can be solid, dotted, dashed etc. line types with or without ending arrows. The line color can be freely selected. By default the regular exit color is being used.
The above example shows 3 different types of user defined exit lines, where the orange one on the left has been selected by the user in order to be edited.
Custom exit lines are purely visual tools and have no effect on the pathfinding, but each custom line must be linked to a valid room exit - either standard or special exit.
Map formats
Whenever a mapping feature is added to Mudlet that requires storing something in the map, the map format version needs to be increased - so older Mudlets can know that a map is too new and they can't load it. To this end, every map has a version number embedded inside it, which you can see by going to mapper settings:
You'll also notice that you have the ability to downgrade a map's version for compatibility with older Mudlets. Be careful when you do so though - features available in the new map won't be available in the older map when you downgrade. Here's a table of all the versions and features:
version | Mudlet version | features |
---|---|---|
20 | 3.16.0 | - Improved way that custom exit line data was held internally, to make coding Mudlet mapper's easier and safer (details). Code is in place to support a workaround to work within map formats back to include version 17. |
19 | 3.8.0 | - added support for more than one of any grapheme (symbol) for the 2D map room symbol. Code is in place to support a workaround to work within map formats back to including version 17. |
18 | 3.0.0 | - keeps player's position when copying to a new profile
- faster map loading |
17 | 3.0.0 | - allows use of setAreaUserData(), setMapUserData(), and related functions |
16 | 2.1 | - doors (visual effect on the mapper that a locked/closed/open door is there)
- exit weights (in addition to existing room weights) |
Mapper tips
General
- Don't move the room you're currently in, you'll go haywire
- The number when spreading/shrinking room selections it the multiplication factor - 2 is a good number to try
Merging areas
To merge two areas together, see this how-to by Heiko. In short:
- Zoom out really far away on the area you'd like to move, and select everything (the selection affects all z-levels as well).
- Right-click, select move to area, and move them to another area. Your selection will still be selected - do not unselect
- Right-click again, select move to position, and move all of your still selected rooms in the new area so it fits.
Zooming the mapper
You can zoom in/out in the mapper using your (vertical) mousewheel. If you'd like to zoom quicker, hold down Ctrl
while doing so!
To set the zoom level via script, use setMapZoom().
It is easy to add your own options to the menu you see when you right-click on your map. To do so, use addMapMenu, addMapEvent, etc.
Mapper favorites
This post here describes how to add a right click menu to your mapper filled with rooms to speedwalk to.
Placing the mapper
Placing the mapper into a corner
Here's a snippet you can use to place the mapper window into a corner and have it automatically come up whenever you open Mudlet. To use this, create a new script (you can make it anywhere) and copy/paste the code into it.
1 local main = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="mapper container"})
2
3 local mapper = Geyser.Mapper:new({
4 name = "mapper",
5 x = "70%", y = 0, -- edit here if you want to move it
6 width = "30%", height = "50%"
7 }, main)
Placing the mapper into its own window

It's possible to create the mapper as a map window (similar to clicking the icon) like this:
myMapWidget = Geyser.Mapper:new({embedded=false})
This will open a map window with your saved layout (if there is one, otherwise it will dock at the right corner)
To choose the position of the DockWindow at creation, use:
-- this will create a map window docked at the left corner
myMapWidget = Geyser.Mapper:new({embedded=false, dockPosition="left"})
Possible dockPositions are: left "l", right "r", top "t", bottom "b" and floating "f"
To change the dockPosition after creation, use:
-- this will change myMapWidget dockPosition to "f" floating
myMapWidget:setDockPosition("f")
Making your own mapping script
If you'd like to code your own mapping script, see the Mapper API and read on for a short tutorial.
To start off, create a new script that'll be included with your mapping script (can even place it into the script folder for your mapping script), and have it do:
mudlet = mudlet or {}; mudlet.mapper_script = true
This'll let Mudlet know that a mapping script is installed, so it won't bother you or whoever else installs your script with a warning that one is necessary.
Next, you want to hook into Mudlet's gotoRoom(id) function and the user clicking on a room in the visual map - for that, define your own doSpeedWalk() function. Mudlet will store the directions / special exits commands your script will need to take in the speedWalkDir table, and the room IDs you'll pass through in the speedWalkPath table:
function doSpeedWalk()
echo("Path we need to take: " .. table.concat(speedWalkDir, ", ") .. "\n")
echo("Rooms we'll pass through: " .. table.concat(speedWalkPath, ", ") .. "\n")
end
speedWalkPath is especially useful for making sure you're still on the path. Most Mudlet mapping scripts keep track of how many rooms along the path they have visited so far and check upon arrival into a new room to make sure it's still on the path.
That's it! (But see below if you want more.)
From here, you'd want to build a walking script that'll send the commands to walk you along the path, along with aliases for the user to use - see the Mapper API functions and Mudlet mapper events.
Adding rooms
To make your first room, do the following steps:
- create an area with setAreaName(areaID, areaname). You can choose any areaID - if you'd like to use the IDs incrementally, see which is the latest from getAreaTable()
- if you want the Mudlet mapper to generate roomIDs for you, get one with createRoomID(). This is an optional step
- create your room with addRoom(roomID)
- give the room coordinates with setRoomCoordinates(roomID, x, y, z). If you're just starting out, put it at 0,0,0 so the room is at the center of the map
- assign your room to an area with setRoomArea(roomID, areaID)
- and finally, call centerview(roomID) to make the map view refresh and show your new room!
Labelling rooms
Rooms have three attributes which you can show on the map:
- an ID. You can't change it; the ID is shown in the room's box when you check "IDs" in the dialog below the map and you're zoomed in far enough.
- a symbol, also displayed in the room's box. You set it with the setRoomChar Lua function, or via the map's context menu.
- a name, typically sent via GMCP. You add it to the map with setRoomName.
The room name can be displayed along with a room's box. Its position defaults to "centered below the room". It is not visible by default because many maps have rooms that are quite close to each other; showing the names by default would create an ugly visual mess.
If you want to enable room names in your mapper, you need to
- stagger rooms. Four or five units' distance instead of one works best if you want to show every label; less is OK if you only show labels when the user asks you to.
- call setMapUserData("room.ui_showName","1"). The existence of this entry controls whether the "Names" checkbox is shown next to "IDs", below the map. This value is zero if the user has unchecked the "Names" checkbox.
- optionally call setMapUserData("room.ui_nameFont","FontName") to change the names' font. The default is the same monospaced font used for the room IDs and symbols.
- call setRoomUserData(room_id, "room.ui_showName","1") to show a room's label. You might want to add an entry to the map's pop-up menu which toggles this.
If the name is misplaced (collision with another room, label, or whatever), you can modify the room's "room.ui_nameOffset" attribute to move it around. The value of this attribute consists of two floating-point values, separated by a space, which offset the room's label (in units of the room box's size). You might want to bind functions that increase or decrease these values to keys like Shift-Control-Arrow and/or Control-Numpad-2468. A hotkey to toggle a room's label display from "on" to "off" and back (e.g. Control-Numpad-5?) is also a good idea.
You also might default to staggering room names. One possible algorithm: if a new room's X coordinate, divided by your default room distance, is an odd number then position its label with an offset like "0 -1.6", which would place it above the room in question. The optimal value for the Y offset depends on the font.
Changes are displayed only when the map is next redrawn.
Font options are global. Overriding them for a single room can be be implemented if requested.
Working with the mapper API
Whenever working with mapper API, keep in mind of the following things:
- You'll want to call centerview after you do some modifications, to get to have the map render your new changes
Translating directions
Several functions in the mapper API take and return #'s for directions - and to make it easier to work with them, you can define a table that maps directions to those numbers in a script with the following:
exitmap = {
n = 1,
north = 1,
ne = 2,
northeast = 2,
nw = 3,
northwest = 3,
e = 4,
east = 4,
w = 5,
west = 5,
s = 6,
south = 6,
se = 7,
southeast = 7,
sw = 8,
southwest = 8,
u = 9,
up = 9,
d = 10,
down = 10,
["in"] = 11,
out = 12,
[1] = "north",
[2] = "northeast",
[3] = "northwest",
[4] = "east",
[5] = "west",
[6] = "south",
[7] = "southeast",
[8] = "southwest",
[9] = "up",
[10] = "down",
[11] = "in",
[12] = "out",
}
Then, using exitmap[input], you'll get a direction number or a direction name. Here's an example that uses it to work out in which directions are the exit stubs available in room 6:
lua local stubs = getExitStubs(6)
for i = 0, #stubs do print(exitmap[stubs[i]]) end
Custom speedwalking and pathfinding

If you'd like to use a custom pathfinding algorithm instead of the built-in one, you can do that:
- Set mudlet.custom_speedwalk = true.
- Your doSpeedwalk script will now see different parameters:
function doSpeedWalk()
echo("Room we're coming from: " .. speedWalkFrom .. "\n")
echo("Room you're going to: " .. speedWalkTo .. "\n")
end
The forum topic Wayfinder contains an example package that implements a shortest-path-first algorithm.
Custom room name search function in the generic_mapper

Sometimes the generic_mapper script is not flexible enough to find the room name in your favorite game. You can create a custom function that handle that search instead of the standard one included in the mapper:
- Type in the input area map config custom_name_search true to enable the usage of the custom function.
- Write your own function called mudlet.custom_name_search. The script call it for your:
mudlet.custom_name_search = function (lines)
-- ...
local line_count = #lines + 1
if string.match(cur_line, " ") then
line_count = line_count - 1
room_name = lines[line_count]
-- map.echo("Name Search: room_nameome:" ..room_name)
elseif string.find(cur_line,prompt_pattern) then
-- ...
return room_name
end
I suggest to start from original name_search function in generic_mapper to avoid common problem.
onVisionFail for generic_mapper - moving through dark rooms
generic_mapper uses a combination of room titles, descriptions and exits to locate your character position in the mapper. Sometimes this information may not be available due to blindness, dark rooms or other affects that may prevent full vision and correct room matching. Using the onVisionFail
event and appropriate triggers you can force your character to move to the next room and update the map accordingly even when vision is limited.
generic_mapper comes with two predefined triggers, add or replace these as necessary with the appropriate lines your game sends.
In these examples when the game sends It is pitch black...
or It's too dark
or It is too dark
starting on a newline (^
character) then it will raise the onVisionFail
event. When called this event will skip looking to match the room, and simply move the character in the direction they sent prior.
Screenshots
Just a few example maps from different players and games:
Here is the full image (17160 x 10120 pixel)
Notes
- ↑ MMP allows for an area ID/area names table to be defined, but Mudlet has no means to verify which definition is the correct one if 2 different area names relate to the same area ID.
Advanced Lua
Lua version
Mudlet uses Lua 5.1.
Lua tables
A good overview of tables is available on Lua's wiki in the TablesTutorial. Nick Gammon has also written a nice overview on how to deal with Lua tables.
How to use multimatches[n][m]
multimatches[n][m]
is the complement of matches[n]
when matching multi-line triggers. multimatches[n][m]
stores its matches by lines, inside each line are the relevant matches to it. The following example can be tested on the game batmud.bat.org:
In the case of a multiline trigger with these 2 Perl regex as conditions:
^You have (\w+) (\w+) (\w+) (\w+)
^You are (\w+).*(\w+).*
The command "score" generates the following output on batMUD:
You have an almost non-existent ability for avoiding hits. You are irreproachably kind. You have not completed any quests. You are refreshed, hungry, very young and brave. Conquer leads the human race. Hp:295/295 Sp:132/132 Ep:182/181 Exp:269 >
If you add this script to the trigger:
showMultimatches()
The script, i.e. the call to the function showMultimatches() generates this output:
-------------------------------------------------------
The table multimatches[n][m] contains:
-------------------------------------------------------
regex 1 captured: (multimatches[1][1-n])
key=1 value=You have not completed any quests
key=2 value=not
key=3 value=completed
key=4 value=any
key=5 value=quests
regex 2 captured: (multimatches[2][1-n])
key=1 value=You are refreshed, hungry, very young and brave
key=2 value=refreshed
key=3 value=young
key=4 value=and
key=5 value=brave
-------------------------------------------------------
The function showMultimatches() prints out the content of the table multimatches[n][m]. You can now see what the table multimatches[][] contains in this case. The first trigger condition (=regex 1) got as the first full match "You have not completed any quests". This is stored in multimatches[1][1] as the value of key=1 in the sub-table matches[1] which, in turn, is the value of key=1 of the table multimatches[n][m].
The structure of the table multimatches:
multimatches {
1 = {
matches[1] of regex 1
matches[2] of regex 1
matches[3] of regex 1
...
matches[m] of regex 1 },
2 = {
matches[1] of regex 2
matches[2] of regex 2
...
matches[m] of regex 2 },
... ...
n = {
matches[1] of regex n
matches[2] of regex n
...
matches[m] of regex n }
}
The sub-table matches[n] is the same table matches[n] you get when you have a standard non-multiline trigger. The value of the first key, i. e. matches[1], holds the first complete match of the regex. Subsequent keys hold the respective capture groups. For example: Let regex = "You have (\d+) gold and (\d+) silver" and the text from the game = "You have 5 gold and 7 silver coins in your bag." Then matches[1] contains "You have 5 gold and 7 silver", matches[2] = "5" and matches[3] = "7". In your script you could do:
myGold = myGold + tonumber( matches[2] )
mySilver = mySilver + tonumber( matches[3] )
However, if you’d like to use this script in the context of a multiline trigger, matches[] would not be defined as there are more than one regex. You need to use multimatches[n][m] in multiline triggers. Above script would look like this if above regex would be the first regex in the multiline trigger:
myGold = myGold + tonumber( multimatches[1][2] )
mySilver = mySilver + tonumber( multimatches[1][3] )
What makes multiline triggers really shine is the ability to react to game output that is spread over multiple lines and only fire the action (=run the script) if all conditions have been fulfilled in the specified amount of lines.
Regex in Lua
Lua has its own, fast and lightweight pattern matching built in - see 20.2 – Patterns. Should you need proper regex however, Mudlet has lrexlib available - which works as a drop-in replacement; replace string. with rex. - for example string.gsub to rex.gsub. See manual for documentation.
-- example: strip out trailing .0's from text using a regex
local stripped = rex.gsub("1.0.0", [[(\.0+)+$]], '')
print(stripped)
The lrexlib manual can be hard to read, so the instructions in this section should provide most of what you need.
lrexlib comes preinstalled in Mudlet and it is automatically bounded to the rex variable, as the rex_pcre version. If you want to test your lua code outside Mudlet, you have to install it yourself. The easiest installation method uses luarocks. There are a few flavors that you can specify, but in this section we will focus on the POSIX and PCRE flavors.
luarocks install --local lrexlib-POSIX
luarocks install --local lrexlib-PCRE
After installation, you can use the library:
> local rex = require("rex_posix")
If you set the flavor to rex_pcre, your code should work afterwards in Mudlet.
Keep in mind that precomputing a pattern with the new function has the advantage that objects resulted will be garbage collected and that regexes are greedy by default.
Another thing that may surprise some users is that, when escaping, you need to backslashes:
> rex.match("The answer is 42", "(\\d+)")
You can also achieve this using long string literal syntax, where you don't need the double escape:
> rex.match("The answer is 42", [[(\d+)]])
There are a few functions that you need to know: gsub, count, split, find, match.
count
The count function counts the matches:
> print(rex.count("ab", "."))
2
A single dot here has the same meaning it has in POSIX regexes.
You can also precompute the pattern, using the new function:
> print(rex.count("ab", rex.new"."))
2
Remember that regexes are greedy by default:
> print(rex.count("aaa", ".*"))
1
split
The split function splits a string according to a regex pattern:
> for a in rex.split("aba", "b") do
print(a)
end
a
a
> for a in rex.split("aba", ",") do
print(a)
end
aba
Be careful though, because while the split consumes all the characters with the same value, if they are adjacent, you will also have the borders between them resulting in an empty string:
> for a in rex.split("abba", "b") do
print(a)
end
a
a
find
The find function searches for the first match, and returns the offsets where the match starts and ends.
> print(rex.find("aaa", "b"))
nil
> print(rex.find("aba", "b"))
2 2
find also takes an additional parameter, which is the starting position:
> print(rex.find("abab", "b"))
2 2
> print(rex.find("abab", "b", 3))
4 4
A negative starting position will circle back from the end:
> print(rex.find("ababab", "b", -1))
6 6
> print(rex.find("ababab", "b", -3))
4 4
match
The match function works similarly to the find function, but returns the matches instead of the indices:
> print(rex.match("abcdef", "ab"))
ab
> print(rex.match("abcdef", ".*"))
abcdef
> print(rex.match("abcdef", "ab.."))
abcd
> print(rex.match("abcdef", ".*", 3))
cdef
> print(rex.match("abcdef", ".*", -3))
def
gsub
The gsub function replaces the pattern in the string, with the value in the third parameter:
> print(rex.gsub("abcdef", "[abef]+", ""))
cd 2 2
This snippet replaces all the "a", "b", "e" or "f" characters with the empty string, so only "c" and "d" remain.
The fourth parameter determines how many replacements are made:
> print(rex.gsub("abcdef", "[abef]+", "", 1))
cdef 1 1
Because the regex is greedy, the "ab" is a single match, so it gets replaced.
PCRE specific functionality
The case insensitive flag:
> rex = require("rex_pcre")
> flags = rex.flags()
> print(rex.find("ABab", "a", 0, flags.CASELESS))
1 1
Coroutines
Mudlet supports Lua's coroutines starting with 3.2.0, which opens up a whole lot of possibilities for the way you program your scripts. A pretty technical description and a tutorial is available, but for a quick explanation, think of coroutines allowing you to pause and resume running a function. If you're familiar with other clients, it is something like a #wait statement where a script will stop running, except unlike a #wait which auto-resumes the script later, you resume it when it yourself whenever you'd like.
Here's an example - add this code as a new script:
function ritual()
send("get wood")
-- think of coroutine.yield as yielding (giving away) control,
-- so the function will stop here and resume on making fire
-- when called the next time
coroutine.yield()
send("make fire")
coroutine.yield()
send("jump around")
coroutine.yield()
send("sacrifice goat")
end
Make a ^ritual$ alias - which seems big, but that's just because there's a lot of explanation inside it:
-- create a coroutine that'll be running our ritual function
-- or re-use the one we're already using if there is one
ritualcoroutine = ritualcoroutine or coroutine.create(ritual)
-- run the coroutine until a coroutine.yield() and see
-- if there's any more code to run
local moretocome = coroutine.resume(ritualcoroutine)
-- if there's no more code to run - remove the coroutine,
-- so next time you call the alias - a new one gets made
if not moretocome then
ritualcoroutine = nil
end
Now try doing the ritual command. You'll see that the send()'s are being sent one at a time, instead of all at once as they would have been without the yields. Cool, huh?
You can also install the demo as a package - paste this into Mudlet:
lua installPackage("http://wiki.mudlet.org/images/3/36/Ritual-coroutine-demo.zip")
Note that if you'll be using coroutines as part of a package you'll give to others, remember about the if mudlet.supportscoroutines then return end
bit. Older Mudlets that don't support coroutines might crash, which sucks. Newer ones that do support them are completely fine, however!
Coroutines have many uses: finite state machines, running intensive tasks (yielding every once in a while so Mudlet isn't frozen), and so on.
Introspective facilities
Lua brings a helpful debug.getinfo(function) function, which gets you some information about where a function comes from: whenever it's your own, or one defined by Mudlet (in C++ or Lua). You can also use it to get more information on the Alias## / Trigger## objects you see in the error console:
If you're working on coding Mudlet itself, use this function to tell where the actual definition of a function is.
Event System
Events in Mudlet allow a paradigm of system-building that is easy to maintain (because if you’d like to restructure something, you’d have to do less work), enables interoperability (making a collection of scripts that work with each other is easier) and enables an event-based way of programming.
The essentials of it are as such: you use Scripts to define which events a function should listen to, and when the event is raised, the said function(s) will be called. Events can also have function parameters with them, which’ll be passed onto the receiving functions.
Registering an event handler via UI
Registering an event handler means that you’ll be telling Mudlet what function it should call for you when an event is raised, so it’s a two step process - you need to tell it both what function you’d like to have called, and on what event it should be called.
To tell it what function should be called, create a new script, and give the script the name of the function you’d like to be called. This is the only time where an items name matters in Mudlet. You can define the function right inside the script as well, if you’d like.
Next, we tell it what event or events this function should be called on - you can add multiple entries. To do that, enter the events name in the Add User Defined Event Handler: field, press enter, and it’ll go into the list - and that is all.
Registering an event from a script
You can also register your event with the registerAnonymousEventHandler(event name, function reference, [one shot]) function inside your scripts:
-- example taken from the God Wars 2 (http://godwars2.org) Mudlet UI - forces the window to keep to a certain size
function keepStaticSize()
setMainWindowSize(1280,720)
end -- keepStaticSize
registerAnonymousEventHandler("sysWindowResizeEvent", keepStaticSize, false)
Template:Note 1: registerNamedEventHandler can also be used. Doing so causes Mudlet to handle saving of the IDs for you. Template:Note 2 Mudlet also uses the event system in-game protocols (like ATCP, GMCP and others).
Raising a custom event
To raise an event, you'd use the raiseEvent() function:
raiseEvent(name, [arguments...])
It takes an event name as the first argument, and then any amount of arguments after it which will be passed onto the receiving functions.
Example of registering and raising an event
Add a script to each profile you need the event.
-- This is the function that will be called when the event is raised.
-- "event" is set to the event name.
-- "arg" is the argument(s) provided with raiseEvent/rasieGlobalEvent.
-- "profile" - Is the profile name from where the raiseGlobalEvent where triggered from
-- It is 'nil' if raiseEvent() was used.
function onMyEvent(event, arg, profile)
echo("Event: " .. event .. "\n")
echo("Arg : " .. arg .. "\n")
-- If the event is not raised with raiseGlobalEvent() profile will be 'nil'
echo("Profile: " .. (profile or "Local") .. "\n")
end
-- Register the event handler.
registerAnonymousEventHandler("my_event", onMyEvent)
To raise the event you can call:
-- Trigger only in the current profile:
raiseEvent("my_event", "Hello world!")
-- Trigger the event in all OTHER profiles:
raiseGlobalEvent("my_event", "Hello World!")
To review, count and extract from an unknown number of arguments received by an event:
function eventArgs(...)
local args = {...}
local amount = #args
local first = args[1]
echo("Number of arguments: " .. amount)
echo("\nTable of all arguments: ")
display(args)
echo("First argument: " .. first)
echo("\n\n")
end
Gamepad functionality
Note: will be removed in 4.18 as this is blocking Mudlet updates and is not used by players.
Gamepad functions are not fully supported with all operating systems and hardware. Windows supports XInput devices like Xbox 360 and Xbox One controllers. DirectInput controllers like a PlayStation 4 controller can be translated to XInput with third party software. Mudlet on Linux can support gamepads but only if you compile it yourself. The automated builds are made using the oldest supported version of Ubuntu, and the Qt5 gamepad module was not available on Ubuntu 18.04 LTS.
Mudlet-raised events
Mudlet itself also creates events for your scripts to hook on. The following events are generated currently:
AdjustableContainerReposition
Raised while a adjustable container is re-positioned.
function repositioningContainer(eventName, containerName, width, height, x, y, mouseAction)
print(f"{containerName}: {x}x, {y}y, {width}x{height}, using mouse? {mouseAction}")
end
registerAnonymousEventHandler("AdjustableContainerReposition", repositioningContainer)
AdjustableContainerRepositionFinish
Raised when an adjustable container done being re-positioned.
function finishedRepositioning(eventName, containerName, width, height, x, y)
print(f"{containerName}: {x}x, {y}y, {width}x{height}")
end
registerAnonymousEventHandler("AdjustableContainerRepositionFinish", finishedRepositioning)
channel102Message
Raised when a telnet sub-option 102 message is received (which comprises of two numbers passed in the event). This is of particular use with the Aardwolf MUD who originated this protocol. See this forum topic for more about the Mudlet Aardwolf GUI that makes use of this.
mapModeChangeEvent
Raised when the mapper is switching between "view-only" and "editing" mode of the Visual Map Editor. A value of "editing" or "viewing" will be given as argument to indicate which mode was entered.
mapOpenEvent
Raised when the mapper is opened - either the floating dock or the in-Mudlet widget.
sysAppStyleSheetChange
Raised when setAppStyleSheet is called and a new stylesheet applied to Mudlet.
-- This will respond to a future (as yet unpublished) addition to the Mudlet code that will allow some
-- of a default application style sheet to be supplied with Mudlet to compensate for some text colors
-- that do not show up equally well in both light and dark desktop themes. That, perhaps, might finally
-- allow different colored texts to be uses again for the trigger item types!
function appStyleSheetChangeEvent( event, tag, source )
if source == "system" then
colorTable = colorTable or {}
if tag == "mudlet-dark-theme" then
colorTable.blue = {64, 64, 255}
colorTable.green = {0, 255, 0}
elseif tag == "mudlet-light-theme" then
colorTable.blue = {0, 0, 255}
colorTable.green = {64, 255, 64}
end
end
end

sysBufferShrinkEvent
Raised when the oldest lines are removed from the back of any console or buffer belonging to a profile because it has reached the limit (either the default or that set by setConsoleBufferSize). The two additional arguments within the event are: the name of the console or buffer and the number of lines removed from the beginning of the buffer. This information will be useful for any situation where a line number is being stored as it will need to be decremented by that number of lines in order to continue to refer to the same line (assuming that it is still present - indicated by the number remaining positive) after the oldest ones have been removed.

sysConnectionEvent
Raised when the profile becomes connected to a MUD.
sysCustomHttpDone
Raised whenever a customHTTP() request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters) and HTTP method.
See also sysCustomHttpError.
sysCustomHttpError
Raised whenever a customHTTP() request fails. Arguments are the error message and the URL that the request was sent to and HTTP method.
See also sysCustomHttpDone.
sysDataSendRequest
Raised right before a command from the send(), sendAll() functions or the command line is sent to the game - useful for keeping track of what your last command was, manipulating input or even denying the command to be sent if necessary with denyCurrentSend().
sysDataSendRequest will send the event name and the command sent (in string form) to the functions registered to it. IE: commandSent in the example below will be "eat hambuger" if the user entered only that into command line and pressed enter, send("eat hamburger"), sendAll("eat humburger", "eat fish") or sendAll("eat fish", "eat humburger")
Note: if you'll be making use of denyCurrentSend(), you really should notify the user that you denied their command - unexperienced ones might conclude that your script or Mudlet is buggy if they don't see visual feedback. Do not mis-use this and use it as keylogger either.
-- cancels all "eat hambuger" commands
function cancelEatHamburger(eventName, commandSent)
if commandSent == "eat hamburger" then
denyCurrentSend() --cancels the command sent.
cecho("<red>Denied! You can't do "..commandSent.." right now.\n")
end --if commandSent == eat hamburger
end
registerAnonymousEventHandler("sysDataSendRequest", cancelEatHamburger)
If you wanted to control input you could set a bool after a trigger. This is useful if you want alias like control, do not know what text will be entered, but do know a trigger that WILL occur just before the user enters the command.
function controlInput(_, command)
if changeCMDInput then
changeCMDInput = false --set this if check to false to it doesn't occur every input
--Also set the bool check BEFORE any send() functions within a sysDataSendRequest function
sendAll(command .. "some target", command .. "some other target", true) --Duplicate and unknown command
denyCurrentSend() --Deny the original command, not the commands sent with sendAll.
end
end
registerAnonymousEventHandler("sysDataSendRequest", controlInput)
Take note that functions registered under sysDataSendRequest WILL trigger with ALL commands that are sent.
sysDeleteHttpDone
Raised whenever a deleteHTTP() request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).
See also sysDeleteHttpError.
sysDeleteHttpError
Raised whenever a deleteHTTP() request fails. Arguments are the error message and the URL that the request was sent to.
See also sysDeleteHttpDone.
sysDisconnectionEvent
Raised when the profile becomes disconnected, either manually or by the game.
If you'd like to automatically reconnect when you get disconnected, make a new Script
and add this inside:
registerAnonymousEventHandler("sysDisconnectionEvent", reconnect)
sysDownloadDone
Raised when Mudlet is finished downloading a file successfully - the location of the downloaded file is passed as a second argument.
Example - put it into a new script and save it to run:
-- create a function to parse the downloaded webpage and display a result
function downloaded_file(_, filename)
-- is the file that downloaded ours?
if not filename:find("achaea-who-count.html", 1, true) then return end
-- read the contents of the webpage in
local f, s, webpage = io.open(filename)
if f then webpage = f:read("*a"); io.close(f) end
-- delete the file on disk, don't clutter
os.remove(filename)
-- parse our downloaded file for the player count
local pc = webpage:match([[Total: (%d+) players online]])
display("Achaea has "..tostring(pc).." players on right now.")
end
-- register our function to run on the event that something was downloaded
registerAnonymousEventHandler("sysDownloadDone", downloaded_file)
-- download a list of fake users for a demo
downloadFile(getMudletHomeDir().."/achaea-who-count.html", "https://www.achaea.com/game/who")
You should see a result like this:
sysDownloadError
Raised when downloading a file failed - the second argument contains the error message, the third the local filename that was to be used and the actual URL used (might not be the same as what was given if redirection took place).
- Example
--if a download fails notify the player.
function downloadErrorEventHandler(event, errorFound, localFilename, usedUrl)
cecho("fuction downloadErrorEventHandler, "..errorFound)
debugc("fuction downloadErrorEventHandler, "..errorFound) --display to error screen in editor
end --function downloadErrorEventHandler
registerAnonymousEventHandler("sysDownloadError", downloadErrorEventHandler)
sysDownloadFileProgress
Raised while file is being downloaded to indicate progess of download.
The arguments passed areː: event name, url of download, bytes downloaded, total bytes (if available).
- Example
-- will show progress bar while download file and hide it after file download is complete
local progressBar = Geyser.Gauge:new({
name="downloadProgressBar",
x="25%", y="10%",
width="50%", height="5%",
})
progressBar:setFontSize(13)
progressBar:setAlignment("center")
progressBar:hide()
local fileUrl = "https://www.mudlet.org/download/Mudlet-4.10.1-linux-x64.AppImage.tar"
local targetFile = getMudletHomeDir() .. "/Mudlet.tar"
function handleProgress(_, url, bytesDownloaded, totalBytes)
if url ~= fileUrl then
return
end
progressBar:show()
if not totalBytes then
bytesDownloaded = 0
totalBytes = 1
end
progressBar:setValue(bytesDownloaded, totalBytes, math.floor((bytesDownloaded / totalBytes) * 100) .. "%")
end
registerAnonymousEventHandler("sysDownloadFileProgress", handleProgress)
function hideProgressBar()
tempTimer(3, function() progressBar:hide() end)
end
registerAnonymousEventHandler("sysDownloadDone", hideProgressBar)
registerAnonymousEventHandler("sysDownloadError", hideProgressBar)
downloadFile(targetFile, fileUrl)

sysDropEvent
Raised when a file is dropped on the Mudlet main window or a userwindow. The arguments passed areː filepath, suffix, xpos, ypos, and consolename - "main" for the main window and otherwise of the userwindow/miniconsole name.

function onDragAndDrop(_, filepath, suffix, xpos, ypos, consolename)
print(string.format("Dropped new file into %s: %s (suffix: %s)", consolename, filepath, suffix))
end
registerAnonymousEventHandler("sysDropEvent", onDragAndDrop)
sysDropUrlEvent
Raised when a url is dropped on the Mudlet main window or a userwindow. As an url at the moment Mudlet understands The arguments passed areː url, schema, xpos, ypos, and consolename - "main" for the main window and otherwise of the userwindow/miniconsole name.

function onDragAndDropUrl(_, url, schema, xpos, ypos, consolename)
print(string.format("Dropped new url into %s: %s (suffix: %s)", consolename, filepath, suffix))
if schema == "http" or schema == "https" then
print("\nOh boy... this might be a link to some website")
end
end
registerAnonymousEventHandler("sysDropUrlEvent", onDragAndDropUrl)
sysExitEvent
Raised when Mudlet is shutting down the profile - a good event to hook onto for saving all of your data.
sysGetHttpDone
Raised whenever a getHTTP() request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).
This event is also raised when a post/put/delete request redirects to a GET.
See also sysGetHttpError.

sysGetHttpError
Raised whenever a getHTTP() request fails. Arguments are the error message and the URL that the request was sent to.
See also sysGetHttpDone.

sysInstall
Raised right after a module or package is installed by any means. This can be used to display post-installation information or setup things.
Event handlers receive the name of the installed package or module as additional argument.
Note: Installed modules will raise this event handler each time the synced profile is opened. sysInstallModule and sysInstallPackage are not raised by opening profiles.

function myScriptInstalled(_, name)
-- stop if what got installed isn't my thing
if name ~= "my script name here" then return end
print("Hey, thanks for installing my thing!")
end
registerAnonymousEventHandler("sysInstallPackage", myScriptInstalled)
sysInstallModule
Raised right after a module is installed through the module dialog. This can be used to display post-installation information or setup things.
See also sysLuaInstallModule for when a module is installed via Lua.
Event handlers receive the name of the installed module as well as the file name as additional arguments.

sysInstallPackage
Raised right after a package is installed by any means. This can be used to display post-installation information or setup things.
Event handlers receive the name of the installed package as well as the file name as additional arguments.

sysIrcMessage
Raised when the IRC client receives an IRC message. The sender's name, channel name, and their message are passed as arguments to this event.
Starting with Mudlet 3.3, this event changes slightly to provide more information from IRC network messages. Data such as status codes, command responses, or error messages sent by the IRC Server may be formatted as plain text by the client and posted to lua via this event.
- sender: may be the nick name of an IRC user or the name of the IRC server host, as retrievable by getIrcConnectedHost()
- channel: may not always contain a channel name, but will be the name of the target/recipient of a message or action. In some networks the name may be that of a service (like "Auth" for example)
- Example
function onIrcMessage(_, sender, target, message)
echo(string.format('(%s) %s says, "%s"\n', target, sender, message))
end
registerAnonymousEventHandler("sysIrcMessage", onIrcMessage)
To send a message, see sendIrc().
sysLabelDeleted
Raised after a label is deleted, with the former label's name as an argument.
sysLoadEvent
Raised after Mudlet is done loading the profile, after all of the scripts, packages, and modules are installed. Note that when it does so, it also compiles and runs all scripts - which could be a good idea to initialize everything at once, but beware - scripts are also run when saved. Hence, hooking only on the sysLoadEvent would prevent multiple re-loads as you’re editing the script.
sysLuaInstallModule
Raised right after a module is installed through the Lua installModule() command. This can be used to display post-installation information or setup things.
Event handlers receive the name of the installed module as well as the file name as additional arguments.

sysLuaUninstallModule
Raised right before a module is removed through the lua uninstallModule command. This can be used to display post-removal information or for cleanup.
Event handlers receive the name of the removed module as additional argument.

sysManualLocationSetEvent
Raised whenever the "set location" command (on the 2D mapper context menu) is used to reposition the current "player room". It provides the room ID of the new room ID that the player has been moved to.

sysMapAreaChanged
Raised whenever the area being viewed in the mapper changes, it returns two additional arguments being the areaID numbers being changed to and the previously viewed area.

sysMapDownloadEvent
Raised whenever an MMP map is downloaded and loaded in.
sysMediaFinished
Raised when media finishes playing. This can be used in a music player for example to start the next song.
Event handlers receive the media file name and the file path as additional arguments.

sysPathChanged
Raised whenever file or directory added through addFileWatch() is modified.
For directories this event is emitted when the directory at a specified path is modified (e.g., when a file is added or deleted) or removed from disk. Note that if there are several changes during a short period of time, some of the changes might not emit this signal. However, the last change in the sequence of changes will always generate this signal.
For files this event is emitted when the file at the specified path is modified, renamed or removed from disk.

- Example
herbs = {}
local herbsPath = getMudletHomeDir() .. "/herbs.lua"
function herbsChangedHandler(_, path)
if path == herbsPath then
table.load(herbsPath, herbs)
removeFileWatch(herbsPath)
end
end
addFileWatch(herbsPath)
registerAnonymousEventHandler("sysPathChanged", herbsChangedHandler)
sysPostHttpDone
Raised whenever a postHTTP() request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).
See also sysPostHttpError.
sysPostHttpError
Raised whenever a postHTTP() request fails. Arguments are the error message and the URL that the request was sent to.
See also sysPostHttpDone.
sysProfileFocusChangeEvent
- Raised whenever a profile becomes or stops being the foreground one when multi-playing, whether multi-view (show all profiles side-by-side) is active or not. The event comes with a second boolean argument which is true if the profile is now the one that has the focus, i.e. will receive keystrokes entered from the keyboard, or false if the focus has just switched from it to another profile.

sysProtocolDisabled
Raised whenever a communications protocol is disabled, with the protocol name passed as an argument. Current values Mudlet will use for this are: GMCP, MDSP, ATCP, MXP, and channel102.
sysProtocolEnabled
Raised whenever a communications protocol is enabled, with the protocol name passed as an argument. Current values Mudlet will use for this are: GMCP, MDSP, ATCP, MXP, and channel102.
function onProtocolEnabled(_, protocol)
if protocol == "GMCP" then
print("GMCP enabled! Now we can use GMCP data.")
end
end
sysPutHttpDone
Raised whenever a putHTTP() request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).
See also sysPutHttpError.
sysPutHttpError
Raised whenever a putHTTP() request fails. Arguments are the error message and the URL that the request was sent to.
See also sysPutHttpDone.
sysSoundFinished
This event is obsolete in Mudlet 4.15. Please replace this with sysMediaFinished()

sysSpeedwalkFinished
Raised when a speedwalk finishes, either one started by speedwalk() or the generic mapping script
sysSpeedwalkPaused
Raised when a speedwalk is paused, either via pauseSpeedwalk() or the generic mapping script.
sysSpeedwalkResumed
Raised when a speedwalk is resumed after pausing, whether it's the generic mapping script or the resumeSpeedwalk() function
sysSpeedwalkStarted
Raised when a speedwalk is started, either by the speedwalk() function or the generic mapping script
sysSpeedwalkStopped
Raised when a speedwalk is stopped prematurely by stopSpeedwalk() or the generic mapping script
sysSyncInstallModule
Raised right after a module is installed through the "sync" mechanism. This can be used to display post-installation information or setup things.
Event handlers receive the name of the installed module as well as the file name as additional arguments.

sysSyncUninstallModule
Raised right before a module is removed through the "sync" mechanism. This can be used to display post-removal information or for cleanup.
Event handlers receive the name of the removed module as additional argument.

sysTelnetEvent
Raised whenever an unsupported telnet option is encountered, allowing you to handle it yourself. The arguments that get passed with the event are type, telnet option, and the message.
sysUninstall
Raised right before a module or package is uninstalled by any means. This can be used to display post-removal information or for cleanup.
Event handlers receive the name of the removed package or module as additional argument.

sysUninstallModule
Raised right before a module is removed through the module dialog. This can be used to display post-removal information or for cleanup.
Event handlers receive the name of the removed module as additional argument.

sysUninstallPackage
Raised right before a package is removed by any means. This can be used to display post-removal information or for cleanup.
Event handlers receive the name of the removed package as additional argument.

sysUnzipDone
Raised when a zip file is successfully unzipped using unzipAsync()
Event handlers receive the zip file name and the unzip path as additional arguments.

sysUnzipError
Raised when a zip file fails to unzip using unzipAsync()
Event handlers receive the zip file name and the unzip path as additional arguments.

sysUserWindowResizeEvent
Raised when a userwindow is resized, with the new height and width coordinates and the windowname passed to the event. A common usecase for this event is to move/resize your UI elements according to the new dimensions.
See alsoː sysWindowResizeEvent
Example
This sample code will echo whenever a resize happened with the new dimensions:
function resizeEvent( event, x, y, windowname )
echo("RESIZE EVENT: event="..event.." x="..x.." y="..y.." windowname="..windowname.."\n")
end
sysWindowMousePressEvent
Raised when a mouse button is pressed down anywhere on the main window (note that a click is composed of a mouse press and mouse release). The button number, the x,y coordinates of the click and the windowname are reported.
Note: Windowname reported in Mudlet 4.9+
See alsoː sysWindowMouseReleaseEvent
Example
function onClickHandler( event, button, x, y, windowname )
echo("CLICK event:"..event.." button="..button.." x="..x.." y="..y.." windowname="..windowname.."\n")
end
sysWindowMouseReleaseEvent
Raised when a mouse button is released after being pressed down anywhere on the main window (note that a click is composed of a mouse press and mouse release).
See sysWindowMousePressEvent for example use.
sysWindowResizeEvent
Raised when the main window is resized, or when one of the borders is resized, with the new height and width coordinates passed to the event. A common usecase for this event is to move/resize your UI elements according to the new dimensions.
See alsoː sysUserWindowResizeEvent
Example
This sample code will echo whenever a resize happened with the new dimensions:
function resizeEvent( event, x, y )
echo("RESIZE EVENT: event="..event.." x="..x.." y="..y.."\n")
end
ttsPitchChanged
Raised when text-to-speech function ttsSetPitch(...) has been called.
See also: Manual:Text-to-Speech
ttsRateChanged
Raised when text-to-speech function ttsSetRate(...) has been called.
See also: Manual:Text-to-Speech
ttsSpeechError
Raised when a text-to-speech function encountered an error while changing states (eg. from stopped to playing to pausing). Usually indicated when the operating system TTS engine is not working correctly.
See also: Manual:Text-to-Speech
ttsSpeechPaused
Raised when text-to-speech function ttsPause(...) has been called.
See also: Manual:Text-to-Speech
ttsSpeechQueued
Raised when text-to-speech function ttsQueue(...) has been called.
See also: Manual:Text-to-Speech
ttsSpeechReady
Raised when the text-to-speech engine is ready to beginning processing text.
See also: Manual:Text-to-Speech
ttsSpeechStarted
Raised when text-to-speech functions ttsSpeak(...) or ttsResume(...) have been called.
See also: Manual:Text-to-Speech
ttsVoiceChanged
Raised when text-to-speech functions ttsSetVoiceByIndex(...) or ttsSetVoiceByName(...) have been called.
See also: Manual:Text-to-Speech
ttsVolumeChanged
Raised when text-to-speech function ttsSetVolume(...) has been called.
See also: Manual:Text-to-Speech
Supported Protocols
Mudlet supports CHARSET, GMCP, MSSP, MSP, ATCP, Aardwolfs 102, MSDP, and the MXP Protocol.
CHARSET, MXP, MSSP, MSP, GMCP and 102 are enabled by default, MSDP can be enabled in settings.
GMCP
Generic Mud Communication Protocol, or GMCP, is a protocol for game servers to communicate information with game clients in a separate channel from the one which carries all of the text that makes up the game itself. Enabling the Debug window will show you GMCP events as they are coming in, and to get an idea of what information is currently stored, hit the Statistics button.
When working with GMCP on IRE games, this GMCP reference is a useful tool.
Using GMCP
Receiving GMCP data
To "trigger" on GMCP messages, you'll need to create an event handler - Mudlet will call it for you whenever relevant GMCP data is received.
As an example, create a new script and give it a name of the function you'd like to be called when the relevant GMCP message is received. Then, add the GMCP event you'd like the function to fire on under the registered event handlers left. Lastly, define the function - either in this or any other script - and you'll be done. The GMCP data received will be stored in the corresponding field of the gmcp table, which your function will read from.
Example:
The test_gmcp() function will be called whenever Char.Vitals is received from the game, and it'll echo the latest data on the screen.
Sending GMCP data
Certain modules will only send data when a request is made by your client. In Mudlet, you can make such a request using the command sendGMCP("command"). Read your game's relevant documentation, such as the IRE document on GMCP, for information about specific modules.
- See Also: sendGMCP
Managing GMCP modules
While some GMCP modules are enabled by Mudlet by default when you connect with a GMCP enabled game, others may not be 'standard' modules and are instead specific to the game itself. In order to provide a way to manage GMCP modules without scripts causing modules in use by other scripts to be disabled.
Registering user
While this step is no longer strictly required, you can register your 'user' with gmod using
gmod.registerUser("MyUser")
Where MyUser is your plugin/addon/whatever name. However, your user will be automatically registered if you enable or disable any modules using it. Which leads us to...
Enabling modules
Enabling a GMCP module is as easy as:
gmod.enableModule("MyUser", "Module.Name")
If MyUser has not been registered previously, then they will be automatically registered when you call this function. An example of a module which would need to be enabled this way is the IRE.Rift module provided by IRE MUDs.
-- add this to a login trigger, or anything that will get done just once per login
gmod.enableModule("<character name>", "IRE.Rift")
Another example would be the Combat module in Lithmeria, which isn't enabled by default:
-- add this to a login trigger, or anything that will get done just once per login
gmod.enableModule("<character name>", "Combat")
Disabling modules
Disabling a GMCP module is just as easy as enabling it:
gmod.disableModule("MyUser", "Module.Name")
The main difference being that the module will be turned on as soon as you enable it if it is not already enabled. If you disable it, it will not be disabled with the server until every user of that module has disabled it. This prevents script A from disabling modules that script B may still be using.
Thorough GMCP tutorial
A good GMCP tutorial that walks you through receiving and sending GMCP data is available here - take a read!
MSDP
MSDP (Mud Server Data Protocol) is a protocol for game servers to communicate information with game clients in a separate channel from the one which carries all of the text that makes up the game itself. Mudlet can be configured to use MSDP by clicking on the Settings button (or Options->Preferences in the menu, or <alt>p). The option is on the General tab.
Once MSDP is enabled, you will need to reconnect to the game so that Mudlet can inform the server it is ready to receive MSDP information. Please note that some servers don't both send MSDP and GMCP at the same time, so even if you enable both in Mudlet, the server will choose to send only one of them.
Enabling the Debug window will show you MSDP events as they are coming in, and to get an idea of what information is currently stored, hit the Statistics button. Also see MSDP reference for some of the commands and values your server might support.
Using MSDP
Receiving MSDP data
To "trigger" on MSDP messages, you'll need to create an event handler - Mudlet will call it for you whenever relevant MSDP data is received.
As an example, lets create a script that'll track whenever we move - that is, the room number changes. To begin with, we need to ask the game to be sending us updates whenever we move - so do:
lua sendMSDP("REPORT", "ROOM_VNUM")
in the command-line first to enable reporting of the room number and name. Then, create a new script and give it a name of the function you'd like to be called when the relevant MSDP message is received. Add the MSDP event you'd like the function to fire on under the registered event handlers - in our case, msdp.ROOM_VNUM. Lastly, define the function - either in this or any other script - and you'll be done. The MSDP data received will be stored in the corresponding field of the msdp table, which your function will read from.
Example:
The test_msdp() function will be called whenever ROOM_VNUM is received from the game, and it'll echo the latest data on the screen.
Sending MSDP data
You can use sendMSDP to send information via MSDP back to the game. The first parameter to the function is the MSDP variable, and all the subsequent ones are values. See the MSDP documentation for some examples of data that you can send:
-- ask the server to report your health changes to you. Result will be stored in msdp.HEALTH in Mudlet
sendMSDP("REPORT", "HEALTH")
-- client - IAC SB MSDP MSDP_VAR "SEND" MSDP_VAL "AREA NAME" MSDP_VAL "ROOM NAME" IAC SE in the documentation translates to the following in Mudlet:
sendMSDP("SEND", "AREA NAME", "ROOM NAME")
- See Also: sendMSDP
Encoding
More and more game servers are looking beyond ASCII encoding to support extended character sets, like UTF-8 encoding, to meet demand for localization of language and the use of emoji characters.
Encoding in Mudlet
Reference our manual page on Unicode for more information on Unicode updating, scripting and trigger support in Mudlet.
Manual Encoding Updates
Mudlet supports manual selection of a server data encoding. Mudlet users may update the server data encoding for a profile by choosing Settings, General and selecting a server data encoding from the corresponding drop-down menu. The server data encoding defaults to ASCII. When the setting is changed, the selected encoding saves with the user's profile information.
Automated Encoding Updates
Negotiating the CHARSET telnet option provides game servers the capability to automatically request a preferred character set with Mudlet per RFC 2066. Game servers may send a telopt WILL CHARSET (42), Mudlet responds with a DO CHARSET (42), then the game server may send SB CHARSET (42) REQUEST (1) <separator_character> <charset>. Mudlet will respond with SB CHARSET (42) ACCEPTED (2) <charset> if it supports that character set. Mudlet will respond with SB CHARSET (42) REJECTED (3) if it refuses the requested character set(s). When Mudlet accepts a requested character set, it automatically updates the server data encoding viewable in the Settings menu. It is possible to send a list of requested character sets to Mudlet by appending additional "<separator_character> <charset>" byte groups to a SB CHARSET (42) REQUEST (1).
Success example:
Server | Mudlet |
---|---|
IAC WILL CHARSET (42) | IAC DO CHARSET (42) |
IAC SB CHARSET (42) REQUEST (1) <space> UTF-8 IAC SE | IAC SB CHARSET (42) ACCEPTED (2) UTF-8 IAC SE |
The following is an example of an attempted negotiation where the encoding was not available with Mudlet:
Server | Mudlet |
---|---|
IAC WILL CHARSET (42) | IAC DO CHARSET (42) |
IAC SB CHARSET (42) REQUEST (1) <space> DEEP-6 IAC SE | IAC SB CHARSET (42) REJECTED (3) IAC SE |
If a Mudlet user does not want to negotiate character set, they may choose the Settings, Special Options menu item in Mudlet and enable "Force CHARSET negotiation off". The following is an example of an attempted negotiation where "Force CHARSET negotiation off" is enabled.
Server | Mudlet |
---|---|
IAC WILL CHARSET (42) | IAC DONT CHARSET (42) |
CHARSET negotiation is available in Mudlet 4.10+.
MSSP
Mud Server Status Protocol, or MSSP, provides a way for game crawlers (i.e. MSSP Mud Crawler) and game listing sites (search for Listings here) to gather detailed information about a game, including dynamic information like boot time and the current amount of online players. It also makes submitting a new game entry very simple on game listing sites. A player or administrator is only required to fill in the hostname and port and other information is gathered from behind the scenes.
MSSP in Mudlet
The MSSP data presented in Mudlet will enable MSSP standard data fields to be made accessible for scripting. Some useful fields include the game name, number of players, uptime, game hostname, game port, codebase, admin contact, Discord invite URL, year created, link to an icon, ip address, primary language, game location, website and several others may be available. It is up to the game in question to populate the data, so don't expect all fields to be filled in.
MSSP is available in Mudlet 4.1+.
Receiving MSSP Data
To receive MSSP data in Mudlet, these conditions must be met:
- The Enable MSSP box in the Settings window of Mudlet must be checked (default on).
- The game must negotiate MSSP with clients like Mudlet at its login screen. Details here.
To see whether your game supports MSSP, after connecting, type lua mssp. If the game does not support MSSP, you will see an empty table mssp = {}. If it does you will see information similar to the example below. The data may be accessed in a similar way to the instructions for GMCP listed above. Typically, MSSP data is only sent once per connection.
mssp = {
HOSTNAME = "stickmud.com",
VT100 = "1",
UPTIME = "1565657220",
MSDP = "0",
MCP = "0",
GMCP = "1",
PORT = "7680",
["MINIMUM AGE"] = "13",
PUEBLO = "0",
INTERMUD = "-1",
SKILLS = "100",
["HIRING BUILDERS"] = "0",
PLAYERS = "6",
CONTACT = "askstickmud@hotmail.com",
CODEBASE = "LDMud 3.5.0 (3.5.1)",
["HIRING CODERS"] = "0",
["PAY FOR PERKS"] = "0",
LOCATION = "Canada",
GAMESYSTEM = "Custom",
MCCP = "0",
SUBGENRE = "Medieval Fantasy",
ROOMS = "10000",
STATUS = "Live",
FAMILY = "LPMud",
LEVELS = "150",
CREATED = "1991",
["PAY TO PLAY"] = "0",
IP = "24.138.28.11",
MOBILES = "-1",
GAMEPLAY = "Hack and Slash",
CLASSES = "8",
NAME = "StickMUD",
SSL = "7670", -- legacy key, use TLS now please!
TLS = "7670",
ANSI = "1",
ICON = "https://www.stickmud.com/favicon.ico",
RACES = "12",
UTF-8 = "0",
AREAS = "-1",
MXP = "0",
HELPFILES = "-1",
["XTERM 256 COLORS"] = "0",
MSP = "1",
OBJECTS = "9780",
WEBSITE = "https://www.stickmud.com",
GENRE = "Fantasy",
DISCORD = "https://discord.gg/erBBxt",
LANGUAGE = "English"
}
MSP
Want to add accessibility and excitement into your game? How about implementing sound and music triggers?
Mud Sound Protocol, or MSP, provides a way for games to send sound and music triggers to clients. Clients have the option to implement a framework where the corresponding triggers play. MSP triggers are sent in one direction to game clients and not to game servers. Sounds may be downloaded manually or automatically if conditions are met.
Games could use telnet option negotiation to signal clients support for MSP (WILL, WONT), and toggling MSP processing on and off (DO, DONT). This is communicated using TELOPT 90, which is reserved (unofficially) for the MSP protocol by our community. Games that do not support telnet option negotiation for MSP should provide a means for their players to toggle this feature on and off.
The latest specification for MSP is located here.
MSP in Mudlet
Mudlet processes MSP sound and music triggers in three ways:
- MSP over OOB - Mudlet is capable of receiving hidden, out-of-band telnet sound and music triggers from game servers via messaging with TELOPT 90.
- MSP for Lua - Mudlet triggers may capture and invoke the receiveMSP function available through the Lua interpreter of Mudlet to process MSP.
- MSP over GMCP - Mudlet may receive GMCP events from game servers sent with the Client.Media package.
Sound or music triggers that contain a media file name will be searched for in the media folder of the corresponding Mudlet profile that matches the host for the game. If the media folder and the file are found by Mudlet, it will be played, given the host's operating system supports playing that type of media file. If the file is not found, Mudlet could initiate a download of the media file when provided a URL to find the file. Alternatively, game administrators may instruct players on other ways to transfer media files by 1) creating a media folder in their game's Mudlet profile and 2) copying files or extracting them from an archive (zip).
MSP is available in Mudlet 4.4+
Receiving MSP Data
Processing of MSP is enabled by default on new game profiles. Control whether the processing is on or off through the Settings menu in Mudlet.
MSP over OOB
Game administrators may send sound and music triggers over the out-of-bounds (hidden) telnet channel encoded with TELOPT 90 after performing telnet negotiation with Mudlet. The advantage to this is that all of the communication is behind the scenes with no additional trigger requirements for the player (see MSP over Lua). Games will send the bytes of out-of-band messages to Mudlet in a format like this:
IAC SB TELOPT_MSP !!SOUND(cow.wav L=2 V=100) IAC SE
Note: Game admins: This option does require a TELOPT 90 WILL message.
MSP for Lua
Check for MSP support with your game and enable any options that allow sound and music triggers to be sent to your screen.
You can download the package from Media:MSP.zip or follow the instructions below.
Create a sound trigger to invoke the Lua interpreter:
Name | Text | Type | Script |
---|---|---|---|
Sound Trigger | ^!!SOUND\((\S+?)(?: (.+))?\)$ | perl regex |
|
Create a music trigger to invoke the Lua interpreter:
Name | Text | Type | Script |
---|---|---|---|
Music Trigger | ^!!MUSIC\((\S+?)(?: (.+))?\)$ | perl regex |
|
Note: Game admins: Best practice is to implement a TELOPT 90 WILL message as a signal to the client that MSP is supported. This is not required.
If your game does not negotiate MSP, you can download Media:MSP-Alternate.zip or you can use this script in your trigger instead of receiveMSP for MSP Sound:
deleteLine()
local mspFile = nil
local mspVolume = 100
local mspLength = 1
local mspPriority = 50
local mspType = nil
local mspURL = nil
-- Strip !!SOUND() from the line
local line = matches[1]:sub(9, -2)
-- Break up the line into tokens
local tokens = line:split(" ")
-- Iterate through the tokens to discover MSP values
for index, value in ipairs(tokens) do
if index == 1 then
mspFile = value
elseif value:find("V=", 1, true) == 1 or value:find("v=", 1, true) == 1 then
mspVolume = tonumber(value:sub(3))
elseif value:find("L=", 1, true) == 1 or value:find("l=", 1, true) == 1 then
mspLength = tonumber(value:sub(3))
elseif value:find("P=", 1, true) == 1 or value:find("p=", 1, true) == 1 then
mspPriority = tonumber(value:sub(3))
elseif value:find("T=", 1, true) == 1 or value:find("t=", 1, true) == 1 then
mspType = value:sub(3)
elseif value:find("U=", 1, true) == 1 or value:find("u=", 1, true) == 1 then
mspURL = value:sub(3)
end
end
if mspFile == "Off" and mspURL == nil then
stopSounds()
else
playSoundFile(
{
name = mspFile,
volume = mspVolume,
loops = mspLength,
priority = mspPriority,
tag = mspType,
url = mspURL,
}
)
end
If your game does not negotiate MSP, you can use this script in your trigger instead of receiveMSP for MSP Music:
deleteLine()
local mspFile = nil
local mspVolume = 100
local mspLength = 1
local mspContinue = true
local mspType = nil
local mspURL = nil
-- Strip !!MUSIC() from the line
local line = matches[1]:sub(9, -2)
-- Break up the line into tokens
local tokens = line:split(" ")
-- Iterate through the tokens to discover MSP values
for index, value in ipairs(tokens) do
if index == 1 then
mspFile = value
elseif value:find("V=", 1, true) == 1 or value:find("v=", 1, true) == 1 then
mspVolume = tonumber(value:sub(3))
elseif value:find("L=", 1, true) == 1 or value:find("l=", 1, true) == 1 then
mspLength = tonumber(value:sub(3))
elseif value:find("C=", 1, true) == 1 or value:find("c=", 1, true) == 1 then
if tonumber(value:sub(3)) == 0 then
mspContinue = false
else
mspContinue = true
end
elseif value:find("T=", 1, true) == 1 or value:find("t=", 1, true) == 1 then
mspType = value:sub(3)
elseif value:find("U=", 1, true) == 1 or value:find("u=", 1, true) == 1 then
mspURL = value:sub(3)
end
end
if mspFile == "Off" and mspURL == nil then
stopMusic()
else
playMusicFile(
{
name = mspFile,
volume = mspVolume,
loops = mspLength,
continue = mspContinue,
tag = mspType,
url = mspURL,
}
)
end
MSP over GMCP
Reference Mudlet's documentation on the MUD Client Media Protocol specification for more information.
Note: Game admins: Do not implement a TELOPT 90 WILL message exchange when exclusively using this option.
MSP Troubleshooting
- Wildcards ? or * within the file name do not trigger automatic sound or music downloads. Ensure the sound was downloaded previously prior to using a wildcard.
- Mudlet < 4.11 would not play the MSP sound if it had unknown elements, Mudlet 4.12+ will ignore the unknown elements and do the best it can to play the sound.
MSP Specification
For more insight into the syntax of sound and music triggers, please reference the specification.
Sound packs
As most games have been around for a long time, they often use Mud Sound Protocol (MSP) to play sounds. We often find that the game administrators have documented a downloadable soundpack on their website, or that a 3rd party has made one. In Mudlet, a profile is created for each game, and you can manually create a media folder inside of it and drop in the media files (sound, music). For games using MSP, you can create simple triggers to play them which are documented above.
ATCP
Mudlet includes support for ATCP. This is primarily available on IRE-based MUDs, but Mudlet's implementation is generic enough such that any it should work on others.
Note: ATCP has been overtaken by GMCP, prefer to use that instead.
The latest ATCP data is stored in the atcp table. Whenever new data arrives, the previous is overwritten. An event is also raised for each ATCP message that arrives. To find out the available messages available in the atcp table and the event names, you can use display(atcp).
Note that while the typical message comes in the format of Module.Submodule, ie Char.Vitals or Room.Exits, in Mudlet the dot is removed - so it becomes CharVitals and RoomExits.
- Example
room_number = tonumber(atcp.RoomNum)
echo(room_number)
Triggering on ATCP events
If you’d like to trigger on ATCP messages, then you need to create scripts to attach handlers to the ATCP messages. The ATCP handler names follow the same format as the atcp table - RoomNum, RoomExits, CharVitals and so on.
While the concept of handlers for events is to be explained elsewhere in the manual, the quick rundown is this - place the event name you’d like your script to listen to into the Add User Defined Event Handler: field and press the + button to register it. Next, because scripts in Mudlet can have multiple functions, you need to tell Mudlet which function should it call for you when your handler receives a message. You do that by setting the Script name: to the function name in the script you’d like to be called.
For example, if you’d like to listen to the RoomExits event and have it call the process_exits() function - register RoomExits as the event handler, make the script name be process_exits, and use this in the script:
function process_exits(event, args)
echo("Called event: " .. event .. "\nWith args: " .. args)
end
Feel free to experiment with this to achieve the desired results. A ATCP demo package is also available on the forums for using event handlers and parsing its messages into Lua datastructures.
Mudlet-specific ATCP
See ATCP Extensions for ATCP extensions that have been added to Mudlet.
Aardwolf’s 102 subchannel
Similar to ATCP, Aardwolf includes a hidden channel of information that you can access in Mudlet. Mudlet deals with it in the same way as with ATCP, so for full usage instructions see the ATCP section. All data is stored in the channel102 table, such that you can do:
display(channel102)
... to see all the latest information that has been received. The event to create handlers on is titled channel102Message, and you can use the sendTelnetChannel102(msg) function to send text via the 102 channel back to Aardwolf.
-- Function for detecting AFK status on Aardwolf mud.
function amIafk()
for k,v in pairs(channel102) do
if k==100 and v==4 then
return true
end
end
return false
end
MXP
MXP is based loosely on the HTML and XML standards supported by modern web browsers. It is only "loosely" based upon these standards because games require dynamic, streaming text, rather than the page-oriented view of web browsers. Also, the existing standards are needlessly verbose for use on a game where text efficiency is important.
In addition, there are additional security concerns to worry about with MXP. While support for HTML tags within a line is desired, players on a game can exploit this power and cause problems. Certain HTML functions need to be restricted so that players cannot abuse them. For example, while it might be desirable to allow players to change the font or color of their chat messages, you would not want to allow them to display a large graphics image, or execute script commands on the client of other users. MXP handles this by grouping the various tags and commands into secure and open categories, and preventing the secure tags from being used by players.
Mudlet implements a subset of MXP features - the most popular ones that are actually in use. Mudlet supports MXP links (including send to prompt and open in browser in Mudlet 3.17+), pop-up menus, creation of custom elements, and line modes. As a game admin, you can ask what features are supported with the <SUPPORT>
command.
MXP in Mudlet
Just like GMCP, MXP data is available in the mxp.
namespace and events are raised. To see all MXP events, turn on Debug mode.
function testmxpsend()
print("Text for the link is: ".. mxp.send.href)
print("Commands to do are: ")
display(mxp.send.actions)
print("\n")
end
registerAnonymousEventHandler("mxp.send", "testmxpsend")
Note: Available in Mudlet 4.8+
Receiving MXP Data
Processing of MXP is enabled by default on new game profiles. Control whether the processing is on or off through the Settings menu in Mudlet.
Simple example of receiving MXP Data (Server owners)
<SEND href=\"&text;\"> go north... </SEND>"
This creates a clickable link that will enable the player to navigate without typing the directions into Mudlet. MXP sends the data immediately when clicked.
Advanced example of receiving MXP Data (Server owners)
<send href='examine "&name;"|get "&name;"' hint='Right mouse click to act on this item|Get &desc;|Examine &desc;|Look in &desc;' expire=get>\" ATT='name desc'>
This creates a clickable link that will 'examine' an item. It also enables a right-click function wherein the player can select to either examine or get the item (in this case &name; is the item and &desc; is the item's description ).
MXP Specification
MXP was originally developed and supported by the Zuggsoft team. For more insight into the syntax, reference the specification. Mudlet has a partial implementation version 1.0 of the MXP spec - to see what is supported, ask Mudlet with the <SUPPORT> tag.
Secure connection (TLS)
To connect to a game securely, tick the 'Secure' box in the profile connection settings:
Note that the game must support a secure (TLS) connection in order for this to work, and this feature is available in Mudlet 3.17+.
If you are a games admin/developer, check out this or this example on how to setup a secure connection to your game, as well as MSSP data in order to let Mudlet know that you do have a secure connection available.
Secure connection prompt

To encourage enhanced data transfer protection and privacy, Mudlet will respond to the detection of the TLS
(or SSL
legacy) key of MSSP (Mud Server Status Protocol) and prompt a user not on a TLS (Transport Layer Security) connection with a choice to reconnect with the advertised TLS port from MSSP.
If the user selects Yes
, Mudlet automatically updates the port with the TLS
value gathered from MSSP, check-marks the Secure
checkbox on the connection dialog, then reconnects. If the user selects No
, Mudlet automatically updates a profile preference so they are not asked again for the current profile, then reconnects. This preference may be controlled on the Settings->Connection menu. This preference is enabled by default.
Adding support for a telnet protocol
In addition to supporting ATCP, GMCP, Aardwolf's 102 and MXP, Mudlet has open telnet support - meaning that for any telnet protocol it doesn't support, it has the tools you can use to build the support for. This does not mean Mudlet supports other protocols "out of the box" - you will either have to get code that adds the support, or you could create it yourself.
The basic tools that you need are addSupportedTelnetOption(), sendSocket() and the sysTelnetEvent.
Create an event handler that goes off on sysTelnetEvent - which is raised whenever an unsupported telnet option is encountered. Your logic handling will start in this event handler. Once you decide what you'd like to send to the game, use sendSocket() to send raw data as-is. Finally, when your logic is done, use addSupportedTelnetOption() to register your telnet option with Mudlet, so it will respond with telnet DO on a query from the game server. See this MSDP snippet for a barebones example.
API philosophy
Adding a support for a new telnet protocol will involve adding the user-facing API. It best for users if it was in the same style as Mudlets handling of other protocols. To see how it's done exactly, check out GMCP, ATCP or Aardwolf 102 examples - but the gist of it is provided below.
Mudlet has a built-in event system, which is used to broadcast messages in an independent way. With it, people can "trigger" on 102, ATCP or GMCP events with Lua functions that get called whenever an event they're interested in is raised. Use the event system to provide your users with a way to react to new protocol data.
Events have names, and optionally, any amount of data with them. For protocol support, Mudlet prefixes the relevant message received name with the protocol name in lowercase. For example, an ATCP Char.Vitals getting updated would raise an event titled "atcp.Char.Vitals". A GMCP Room.Info message would raise a "gmcp.Room.Info" message.
Additionally, Mudlet also allows catch-all event - in case the user wants to use one event handler for a variety of sub-events (it's not uncommon for games to use Main.Sub.Add, Main.Sub.Remove, Main.Sub.List to keep track of a list, for example, while conserving data). To accomplish this, it raises events for every relevant namespace - that is, a Main.Sub.Add event will raise protocol.Main.Sub and protocol.Main.Sub.Add events. While it is entirely possible for one event handler to react to multiple events, this is provided for convenience.
For storing protocol data, Mudlet uses an aptly named global table - gmcp for GMCP data, atcp for ATCP data. Data is stored in the same way it is received and the event is raised for - so a Char.Vitals message's contents will be stored in gmcp.Char.Vitals, a Room.Info's contents in gmcp.Room.Info. If there were was any nested data within the message, it is stored as a table within the proper namespace - ie, a "details" JSON array of a GMCP Room.Info message would be stored in gmcp.Room.Info.details. Use a global table with the protocol name in lowerspace for storing permanent data that your users will read from.
That's it! If you'll need any Mudlet-related help, feel free to post on our forums. Once you're done, package your work for distribution which you can optionally post in the finished scripts section.
What is a Mudlet package
It's a zip file that ends with .mpackage or .zip that contains xml files to import along with any resources a package might have (images, sounds and etc), or simply an .xml file on its own. Packages can be installed / uninstalled via a window in Mudlet.
You'll see packages represented in brown in the script editor everywhere - triggers, aliases, etc. All items of a package have to go into a package folder that they belong in - so the user can know which package do items belong to, and modify the package for their needs (if it didn't have a folder, then you wouldn't be able to 'add' anything to a package).
Where to find Mudlet packages
Check out the Scripts & Packages section on Mudlet forums for an excellent selection of Mudlet packages.
Some Mudlet packages may also be exlusively available on your own game-specific website or forums, so make sure to check out what your game has to offer as well.
What is a Mudlet module
It's the same thing as a Mudlet package - the only difference is how you import it: via the Module manager instead of the Package manager, and what happens after: Mudlet will save the module back to the original file instead of the profile save file. This means the original xml or mpackage (in Mudlet 4.14+) will automatically get updated. Really useful if you're writing Mudlet code to share with others - you won't have to ever manually export it again, Mudlet will do it automatically for you! You can version your modules using Git using this way.
You can also share a module across several profiles and automatically keep it in sync by installing the module in the relevant profiles and ticking the "sync" option in all of them.
If you'd like your module to be loaded before all the scripts in a Mudlet profile, you can do that with the -1
module priority.
How to install a Mudlet package
as a package
Drag and drop the link to the package into Mudlet (4.11+) or the the package file itself (as of 4.8+) and it'll get installed. The package will then get merged into the Mudlet profile and the original file can be deleted.
Alternatively, Toolbox→Package Manager will open the window where you can hit 'Install'.
as a one-liner
In the command line:
lua installPackage"http://<online package location>"
as a module
Use Toolbox→Module Manager to install a module.
from the game
Packages can also be auto-installed from the MUD server via ATCP or GMCP - see ATCP extensions or GMCP extensions for more.
Module best practices
Are you making a Mudlet package? We keep a list of some best practices we've accumulated over the years at Manual:Best_Practices#Package_and_Module_best_practices
There are some decisions you can make that are outside of best practices, but will influence things:
- write all code inside Mudlet, or outside Mudlet in .lua files?
- If you want more contributors you may find it better to use the built in Mudlet editor, as more of the Mudlet userbase is familiar with it.
- If you want the power of a full IDE or dislike XML diffs in your SCM, then use the latter, see muddler, an unofficial tool for Mudlet packages.
Create a Mudlet package with Mudlet Profile Exporter
Mudlet provides an export dialog for saving a subset of a profile's settings and configuration to a file.
Exported settings are saved into a package that can be imported using Package Manager > Install new package.
Package information
Each new package requires a name or use the dropdown menu to update a currently installed package. Select the profile configuration and definitions to be exported using the interface. For simple exports, this information is enough to create a file.
To build a Mudlet package following best practices, use the Package optional details by pressing (optional) add icon, description, and more to define additional metadata and provide information to Mudlet users that choose to import your package.
Package optional details
The optional details allow setting:
- Author information
- An icon, 512x512 recommended
- A description for those interested in learning more, and documenting any features or a short changelog
- A version number
You can use Github-flavoured markdown in the package description to give a nice presentation for the player. For inspiration on creating good quality descriptions, check out packages here and here.
External data, dependencies
If your package requires other Mudlet packages, add them under the Required packages dropdown. For example creating a set of custom triggers for a game to use with generic_mapper.
Packages that reference local files such as in the Including images, sounds, and other files section below will need to declare them in this section, to export them for reuse. Without these files the package may work locally but not on another's computer.
To remove an included asset, select it from the list and use backspace (fn + delete on macOS) to remove it.
NOTE: To remove a dependency that has already been selected and added, use CTRL+Delete (Linux/Windows) or FN+Backspace (MacOS).
Save exported profile
Mudlet will put the exported package on the current user's desktop by default. Use Select export location to pick a different destination.
Export to write the package, Close to exit
Create a Mudlet package by hand
Alternatively, you can create a package by hand - it's zip file that ends with either .mpackage (preferred) or .zip. Include all xml's that you'd like to be installed in the top level folder of the package - that is, don't have them within a folder in the archive - just have them be upfront.
Naming the package
Add a file at the top level of the package (so not inside any folders in the package) called config.lua that has the following line to name your package:
mpackage = "<name of your package>"
That's it. If you don't include config.lua, Mudlet will then deduce the package name from the file name.
Including images, sounds, and other files
If you'd like to include other folders or files in the package, you can - they will be copied into getMudletHomeDir().."/"..packagename upon installation, so your scripts can use them. Since Mudlet 3.10 you can include font files (.otf or .ttf) and they will be automatically available for your scripts to use.
For example, if your package is called "sipper" and you have health.png as an image in it, you can place on a label like so:
-- you don't have to worry about \ versus / for file paths - use / everywhere, Lua will make it work on Windows fine
setBackgroundImage("my health label", getMudletHomeDir().."/sipper/health.png")
Install the one-liner package demo above for an example of how to make use of images in packages.
Using .lua files
As of Mudlet 3.6.2 you can require "myfile"
to load myfile.lua from the package folder.
As an example, if you have your package sipper, using a custom echo function named sipperecho defined in customFunctions.lua you can
require "sipper.customFunctions"
sipperecho("I work")
Alternatively you can rename customFunctions.lua to init.lua, this will allow you to require "<name of your package>"
and
require "sipper"
sipperecho("I work")
What is a screen reader
The term, "Screen reader", refers to a piece of software on a computing device that is capable of examining the screen of the device and relaying that information to someone who is blind or visually impaired through the use of synthetic speech or Braille. Screen readers exist on desktops, laptops, mobile devices, and even gaming consoles.
Screen reader agnostic tips
Quick Accessibility Configuration
Mudlet comes with a command that works with every new profile you create. The purpose of this command is to perform certain operations on Mudlet itself, not the MUD you're connected to.
The two commands that are relevant to screen reader users are:
mudlet access on
mudlet access reader
Typing in the first command will set a few things up that'll make the experience better for screen reader users, among which is setting Ctrl+Tab
as the shortcut to change focus between the input line and the main window.
The second command will install an optional package called Reader which was initially designed to improve the state of accessibility on Mac OSX, but offers some additional features for Windows and Linux as well.
Holding Alt to open the menubar currently does not work. As a workaround, Alt+P opens preferences and Alt+E opens the script editor.
Input line
Sent commands are selected and kept in the input line by default, which is useful for sighted users. To make it easier for screen readers, go to preferences - Input line tab - and Set the following options as indicated:
- "Auto clear the input line after you sent text", should be checked
- "Show the text you sent", should be unchecked
Main Window
To switch between the input line and the main window, please first select a hotkey under the, "Special Options" tab. Your choices are:
Tab
CTRL+Tab
F6
Once a hotkey has been selected, it will allow you to review text using the following shortcuts -
Output review shortcuts | |
---|---|
Left, Right, Up, Down | Navigate letter by letter |
Ctrl+Left, Ctrl+Right | Navigate word by word |
Shift+Left, Right, Up, Down | Select text letter by letter |
Ctrl+Shift+Left, Right, Up, Down | Select text word by word |
Home | Go to the beginning of the line |
Ctrl+Home | Go to the beginning of the window (first line, first letter) |
End | Go to the end of the line |
Ctrl+End | Go to the end of the window (last line, last letter) |
PageUp | Jump a visual window's height up |
PageDown | Jump a visual window's height down |
Ctrl+C | Copy selection |
Ctrl+Shift+C | Copy selection as HTML |
Special Options
Briefly touched on in the section above, there are a few options in this tab of the preferences dialog designed to aid screen reader users.
Announce incoming text in screen reader
Speaks out text coming from the game using the screen reader, on by default. Turning this option off is relevant to macOS and Linux.
Blank Lines
When the game sends blank lines:
- Show them
- Hide them
- Replace with a space
It may be advantageous to select either of the latter two options, as having blank lines can be problematic on Windows specifically.
Switch To Reviewing Main Window
Switch between input line and main window using:
Tab
CTRL+Tab
F6
When a key is selected from this dropdown list, it will toggle between placing focus in the main window so that normal cursor commands can be used to review it as well as selecting text and copying it. Note that this should be configured, as it is set to, "No key", by default. N.B. When the tab key is set, the autotab completion functionality will be lost.
Nested triggers
In Mudlet, triggers can have a parent/child relationship. But for those new to creating triggers, this may not be what you want. At this time, this relationship is not indicated by screen readers. To ensure that you are not creating a child trigger, arrow up to the top of the list. You'll hear the announcement, "Triggers". When you do so, and you click the, "Add Item" button, you are guaranteed to create a trigger that is not grouped under one of your previous ones.
To quickly navigate between the triggers list, trigger name, patterns list, and the code editor, use Ctrl+Tab
. It'll cycle between those elements in exactly that order, allowing you to jump around the screen to the most important parts.
Screen Reader and Operating System Specific Information
The pages linked below will serve to detail how to use Mudlet with a screen reader. As Mudlet is a cross-platform client, hints and tips to get the most out of using it will be given for each of the platforms it's available on.
Screen reader tips for game admins
The following are tips that can help MUD owners/administrators make their games more accessible to screen reader users.
Auto-detection
Auto-detection of visually impaired players is frowned upon, as it could lead to 'fingerprinting' certain users without their consent. Instead, the best practice is to provide a command for the players that enables a screenreader-friendly mode instead - see StickMUD as an example.
Sounds
Sounds are a great way of letting a blind or visually impaired user know that something has happened. Especially during fast-paced activities such as combat. They can be as simple as alerts, such as chats or tells, to a full on experience complete with combat sounds, music, and ambiances.
Sounds can either be sent by the server and downloaded to the client, or can be made using triggers by the player. MSP, GMCP, and MSDP can all be used to accomplish this.
Avoid ASCII Art
ASCII art can be a major hindrance to screen reader users. If your MUD has a lot of ASCII art, please consider creating a blind mode, or screen reader mode that can be switched on at any time. Optionally, asking new accounts/characters whether or not they're using a screen reader during character generation and then setting a flag or series of flags to tailor the display is wonderful, because screen reader users do not have to remember a list of options to toggle on and off. ASCII art on the start screen isn't a huge problem, as most often, a blind or visually impaired player will read through it once and then not need to again. The goal here is not to take away anything from sighted players.
Tables
Presenting information in tabular format can be a great way to visualize data for a sighted user, but when a screen reader user tries to read this table, they do not have the ability to walk through the cells. This is because, while screen readers do in fact provide table navigation commands, they require markup which isn't present in plain text. Please consider breaking up the information into lines with commas or colons which will make things much clearer. Tables in MUDs can often appear as streams of indecipherable data.
more tips?
I'd recommend checking out legends of the Jedi as they have done a good effort when it comes to making their mud accessible, just as an example. also you could reach out and talk to us in Mudlet's accessibility channel in discord, we'd be happy to help.
Third party packages
Here are some third party packages which we think are useful for Mudlet.
Mudlet Reader package
This package provides shortcuts for reading output, and fixes some VoiceOver issues regarding queuing things. It can be installed by using the built-in 'mudlet access reader' alias.
Download it here.
Quick Output
This package adds the ability to read the ten most recent lines from the MUD as well as copy a given line to the clipboard. More information can be found here
Channel History
This package provides a virtual buffering system for use in triggers which can be reviewed at any time using easy-to-remember hotkeys. Each message that is stored in a buffer is also assigned a category by the trigger author. Thus, things like public chats, tells, game announcements, etc. can each have a separate category. To learn more about this package, click here.
Scripting with Mudlet
Lua tables can basically be considered multidimensional arrays and dictionaries at the same time. If we have the table matches, matches[2] is the first element, matches[n+1] the n-th element.
a = "Tom"
matches[2] = "Betty"
b = matches[2]
c = a .. b and e will equal "TomBetty"
To output a table you can use a convenience function - display(mytable), which is built into Mudlet.
Lua interface functions - triggers, timers etc.
How to get data from regex capture groups? Regular expression capture groups (e.g. "(\d+)" ) are passed on to Lua scripts as a Lua table matches. To make use of this information inside Lua scripts, you need to specify the number of the capture group within the regex.
Example: You have (\d+) weapons and they are (?:(\b\w+\W+)+)
This regex contains 3 capture groups, but only the 2 green colored ones contain data as the red capture group is a non-capturing group. Consequently, your Lua script gets passed only 2 instead of 3 capture groups and matches[4] is undefined.
In your Lua script you may write following program in order to print the number and status of your weapons on the screen:
You have (\d+) weapons and they are (?:(\b\w+\W+)+)
number_of_weapons = matches[2]
status_of_weapons = matches[3]
notice = number_of_weapons .. status_of_weapons
echo( notice )
send( "put weapons in backpack" )
-- the following 2 lines color the first capture
-- group red and the second group blue
-- see below for details
selectCaptureGroup( 2 )
setFgColor( 255,0,0 )
selectCaptureGroup( 3 )
setFgColor( 0,0,255 )
The best way is to use selectCaptureGroup( number ) to select the proper capture group and then perform your actions on it e.g. replace(), highlight etc. Note: Both selectCaptureGroup() and matches[n] start with group 1 (which is the whole match. The defined capture groups start with 2).
How to select all occurrences of "Tom" and highlight them?
You add a function like this to a script containing you main function definitions. Note that script items differ from all other "scripts" in triggers, timers, actions etc. because they require you to put your code in proper functions that can be called by your other trigger-scripts, timer-scripts etc. via normal function calls. Trigger-scripts, timer-scripts etc. cannot contain any function definitions because they are automatically generated functions themselves because this makes usage a lot easier.
To come back to our question how to select all occurrences of "Tom" and highlight them:
function setBgColorAll( word, r, g, b )
i = 0
word_count = 1
while i > -1 do
i = selectString(word, word_count)
if i == -1 then
return
end
word_count = word_count +1
setBgColor( r, g, b )
end
end
Then you simply define a substring matching trigger on the word "Tom" and in the trigger script you call above function:
setBgColorAll("Tom", 255,50,50)
Since Mudlet 4.11+ it is possible to use name capture groups. You can verify if feature availability by checking mudlet.supports.namedPatterns
flag.
Let's say you have multiple patterns that you want to handle with one code.
^My name is (?<name>\w+)\. My class is (?<class>\w+)\.
^I am (?<class\w+)\ and my name is (?<name>\w+)\.
Notice that class and name come in different order, therefore in first case we will have name under matches[2]
and in second case under matches[3]
.
With named capture groups in both cases we will have name available under matches.name
and class under matches.class
.
Code example to handle named matches above:
echo("Name: " .. matches.name .. "\n")
echo("Class: " .. matches.class .. "\n")
Sending commands or printing information messages
To print information messages on the session screen you can use the echo( message ) function, or insertText( text ). Currently, it only takes one string as argument.
To send a command to the MUD, you can use the send( command ) function. In Alias scripts the command that is being sent to the MUD is contained in the variable command that you can change in the context of Alias scripts. Alias take regular expressions, as well. As a result, you can use following regex and script to talk like Yoda: Perl regex:
say (\w+).*(\w*).*(.*)
script:
send( "say " .. matches[4] .." " .. matches[2] .." ".. matches[3] )
Note: The variable "command" contains what was entered in the command line or issued via the expandAlias( ) function. If you use expandAlias( command ) inside an alias script the command would be doubled. You have to use send( ) inside an alias script to prevent recursion. This will send the data directly and bypass the alias expansion.
Changing and formatting text from the MUD
When sending commands to the MUD - from now on referred to as output stream - alias scripts find the command that was issued by the user stored in the variable "command".
By manipulating the value, the command can easily be changed before it is being sent to the MUD.
However, things get much more complicated with the data received from the MUD, from now on referred to as input stream. Before triggers can be run on the MUD data, Mudlet has to strip all format codes from the text and store it in data structures associated with the text. Consequently, the text that is being passed on to the trigger processing unit is a small subset of the data received from the MUD. If you want to edit, replace, delete or reformat text from within your trigger scripts you have to keep this in mind if you don’t want to lose all text format information such as colors etc.
As the text is linked with data structures containing the format of the text, the cursor position inside the line is important if data is being changed. You select a word or a sequence of characters from the line and then issue commands to do actions on the selected data.
Replacing the word "Tom" with "Betty" in the line: Jim, Tom and Lucy are learning a new spell. This could be done with following script:
selectString("Tom",1)
replace("Betty")
Things get more complicated if there are two or more occurrences of "Tom" in the line e.g. Jim and Tom like magic. Jim, Tom and Lucy are learning a new spell.
The above example code would select the first occurrence of "Tom" in this line and ignore the second. If you want to work on the the second occurrence of "Tom" you have to specify the occurrence number in the call to select().
selectString( "Tom", 2 )
replace( "Betty" )
This code would change the second "Tom" and leave the first "Tom" alone. The function call
replaceAll( "Betty" )
will replace all occurrences of "Tom" with "Betty" in the line if "Tom" has been selected before. replaceAll() is a convenience function defined in LuaGlobal.lua.
Colorization example: You want to change to color of the words "ugly monster" to red on a white background.
You add a new trigger and define the regex: ugly monster In the script you write:
selectString("ugly monster", 1 )
setFgColor(255,0,0)
setBgColor(255,255,255)
resetFormat()
Another means to select text is to select a range of characters by specifying cursor positions. If we have following line: Jim and Tom like magic. Jim, Tom and Lucy are learning a new spell.
selectSection( 28, 3 )
This example would select the second Tom. The first argument to selectSection is the cursor position within the line and the second argument is the length of the selection.
selectCaptureGroup( number )
This function selects the captureGroup number if you use Perl regular expressions containing capture groups. The first capture group starts with index 1.
Deleting Text - Gagging
deleteLine()
This function deletes the current line - or any line where the cursor is currently placed. You can use repeated calls to this function to effectively erase the entire text buffer. If you want to delete or gag certain words only, you can select the text that you want to delete and then replace it with an empty string e.g:
If you get this line form the MUD: "Mary and Tom walk to the diner."
selectString( "Tom", 1 )
replace( "" )
Then the output will be changed to: "Mary and walk to the diner."
Cursor Movement and Cursor Placement
Mudlet allows you to insert text arbitrarily within the buffer - in the previous line, in the previous ten lines, or even the first line that you've ever saw. These are the tools to help you with the job:
moveCursor( windowName, x, y )
This will move the user cursor of window windowName to the absolute (x/y) coordinates in the text.
moveCursor( "main", 20, 3950 )
will move the cursor on the 20th character from the left on line number 3950. To determine the current cursor position you can use getLineNumber() and getColumnNumber() as well as getLastLineNumber() to get the number of the last line in the text buffer. moveCursorEnd("main") will move the cursor of the main display to end of the buffer. This is always a new line of size 1 containing the character \n.
number_of_last_line_in_text = getLineCount()
returns the number of the last line of the text in the console buffer. This number will change as soon as a new \n is printed either by the user or when a new line arrives from the MUD. All lines from the MUD are terminated with \n which is called line feed or the new line character. This control character ends the current line and move the cursor to the beginning of the next line, thus creating a new, empty line below the line that contains the \n.
line_number_of_the_current_cursor_position = getLineNumber()
column_number_of_the_current_cursor_position = getColumnNumber()
luaTable_containing_textlines = getLines( absolute_line_number_from, absolute_line_number_to )
this will return a Lua table containing all lines between the absolute positions from and to.
Note: This function uses absolute line numbers, not relative ones like in moveCursor().
moveCursor()
returns true or false depending on whether the move was possible and done.
Inserting text in the middle of the line
Here's an example where we'll append the text (one) right after the word exit in the line of You see a single exit leading west.
The pattern we used was an exact match for You see a single exit leading west.
and the code is:
if moveCursor(string.find(line, "exit")+#("exit")-1, getLineNumber()) then
insertText("(one)")
end
What happened here:
- we triggered on the desired line using our pattern above
- we used moveCursor() to place the cursor in the desired position within the line. moveCursor() takes both the line number and the position within the line to place our virtual cursor on, so
- we used string.find() to find the position of the word "exit" within the line
- but string.find() returns us the position of the first character of the word we want, while we want to have the text be right after it - so we find out how long our word is with
#("exit")
, add that to the number returned by string.find() which gets us the first character + the length of the word - which isn't quite at the end of the word, but the word plus the space (because of string.find() and the first character) - so we substract 1 to move our cursor right at the end of the word - we then use getLineNumber() to get the current line number, so our cursor is placed on the current line, at our desired position
- lastly we finally insert the text with insertText(), which puts the text exactly where our virtual cursor is
Done! You can also use cinsertText() for coloured inserts, and other functions mentioned above and in the API manual to help you do what you'd like.
User defined dockable windows
You may want to use dock windows to display information you gathered in your scripts, or you may want to use them as chat windows etc. Check out Geyser.UserWindow on how to add them!
Dynamic Triggers
triggerID = tempTrigger( substring pattern, code ) creates a fast substring matching trigger
triggerID = tempRegexTrigger( regex, code ) creates a regular expression matching trigger
triggerID = tempBeginOfLineTrigger( begin of line pattern, code ) creates a fast begin of line substring trigger
Scripting howtos
How to convert a string to value?
Say you'd like to capture a number from a trigger, but the capture always ends up being a "string" (or, just text on which you can't do any maths on) even if it's a number. To convert it to a number, you'd want to use the tonumber() function:
myage = tonumber(matches[2])
How to highlight my current target?
You can put the following script into your targetting alias:
if id then killTrigger(id) end
id = tempTrigger(target, function() selectString(target, 1) fg("gold") deselect() resetFormat() end)
Where target is your target variable. Note that you have to use the full name, capitalized. If you’d like the script to auto-capitalize for you, you can use this version:
target = target:title()
if id then killTrigger(id) end
id = tempTrigger(target, function() selectString(target, 1) fg("gold") deselect() resetFormat() end)
Note: Ensure you're on Mudlet 3.5.0+ so you can put function() in a tempTrigger().
How to format an echo to a miniConsole?
One of the ways you can create multi-line displays in a miniConsole with variable information is with string.format and the use of [[ ]] brackets for text, which allow for multiple line in text:
local WindowWidth, WindowHeight = getMainWindowSize();
createMiniConsole("sys",WindowWidth-650,0,650,300)
local name, age, sex = "Bob", 34, "male"
cecho("sys", string.format([[
/---------\
%s
%dyrs
sex - %s
\---------/
]], name, age, sex))
How to play a sound when I receive communication while afk?
For this to work, place the line you'd like to trigger on in the first pattern box and select the appropriate pattern type. Then add return not hasFocus() with the Lua function as the second pattern, enable the AND trigger, and set the line delta to zero. Then just enable play sound, choose your sound and you're set!
How can I make a key that toggles between commands?
To make a key that toggles between two actions, for example - sleep/wake, you can use this as the script:
if not sleeping then
send("sleep")
sleeping = true
else
send("wake")
sleeping = false
end
How can I make a trigger with a next-line condition?
Here's how you can set it up - replace line1 and line2 with appropriate lines.
Here's the Mudlet XML you can download for this!
How to target self or something else?
Using regex and an 'or' statement allows us to consolidate multiple aliases, or an if statement, into a single more simple alias. When a regex is found it will use it, but if you don't specify one then the alternative will be used. The use of 'or' can be used with any function in Mudlet. In this example, one can type "buff" to buff themself, or "buff ally" to buff their ally instead.
^buff(?: (\w+))?$
send("cast buff on "..(matches[2] or "myself"))
How to delete everything between two lines?
When deleteLine() is called, every following line shifts back in numerical position. Thus if we know where we're starting and how many lines to expect, we can use a for loop to gag everything between line a and b by leaving the cursor in one spot. In the below example, line_a_number is the number of the line you want to start at, and line_b_number is the ending line. To gag x number of lines instead, use line_a_number + x in place of line_b_number.
for i = line_a_number, line_b_number, 1
do
moveCursor(0, line_a_number)
selectCurrentLine()
deleteLine()
end
How to capture foreground line color information?
Here's an example that loops through each character in a line of text and prints the character and its foreground color to a miniconsole if the color has changed from the previous character:
Trigger: ^
(regex)
Code:
miniconsoleContainer =
miniconsoleContainer or Adjustable.Container:new({name = "miniconsoleContainer"})
myMiniconsole =
Geyser.MiniConsole:new(
{
name = "myMiniconsole",
x = 0,
y = 0,
autoWrap = true,
color = "black",
scrollBar = false,
fontSize = 8,
width = "100%",
height = "100%",
},
miniconsoleContainer
)
local index = 0
local line = getCurrentLine()
local linesize = #line
local currentlinenumber = getLineNumber()
local r, g, b = 0, 0, 0
local cr, cg, cb -- last seen colors
while index < linesize do
index = index + 1
moveCursor("main", index, currentlinenumber)
selectString(line:sub(index), 1)
r, g, b = getFgColor()
if cr ~= r or cg ~= g or cb ~= b then
cr, cg, cb = r, g, b
myMiniconsole:echo(string.format("rgb(%d,%d,%d)%s", r, g, b, line:sub(index, index)))
else
myMiniconsole:echo(string.format("%s", line:sub(index, index)))
end
line:sub(index, index)
end
myMiniconsole:echo("\n")
How to enter a carriage return / enter command?
Say you'd like to gag the following line, and just continue ...
[ Press Enter to continue ]
Trigger: [ Press Enter to continue ] (set to exact match)
Code: deleteLine()
send("\n")
How to repeat commands with #?
Install the following alias, and with it #5 mycommand
will get repeated five times.
How to move the command line over?
To move the command line over to the right, create a new script and add the following to it:
setCmdLineStyleSheet("main", [[
QPlainTextEdit {
padding-left: 100px; /* change 100 to your number */
background-color: black; /* change it to your background color */
}
]])
How to add a background for Mudlets buttons?
You can give Mudlets buttons a background to have them blend in with your UI by doing this:
-- replace the /home/vadi/Pictures/tile.png location below with the one of your picture!
-- you can download the sample tile.png from https://opengameart.org/content/bevouliin-free-game-background-for-game-developers
local backgroundpath = [[/home/vadi/Pictures/tile.png]]
-- Windows:
-- local backgroundpath = [[C:/Users/Vadim/Downloads/Free game background/transparent PNG/tile.png]]
setAppStyleSheet([[
QToolBar {
border-image: url(]]..backgroundpath..[[);
}
QToolBar QToolButton:!hover {
color: white;
}
QToolBar QToolButton:hover {
color: black;
}
]])
Result:
Advanced scripting tips
Do stuff after all triggers/aliases/scripts are run
This little snippet will have your commands be executed right after, depending on the context you run it in, all triggers, aliases or scripts are completed:
tempTimer(0, [[mycode]])
How to delete the previous and current lines
This little snippet comes from Iocun:
moveCursor(0,getLineCount()-1)
deleteLine()
moveCursor(0,getLineCount())
deleteLine()
db: Mudlet's database frontend
The DB package is meant to provide easier access to a database, so you don’t have to know SQL or use the luasql module to set and get at your data. However, it does require that the luasql module be compiled and included in Mudlet to function.
Creating a Database
Before you can store anything in a database, you need to create one. You may have as many independent databases as you wish, with each having as many unique tables-- what we will call sheets in this package, so as to avoid confusion with Lua tables - think spreadsheets.
To create a database, you use the db:create() function, passing it the name of your database and a Lua table containing its schema configuration. A schema is a mold for your database - it defines what goes where. Using the spreadsheet example, this would mean that you’d define what goes into each column. A simple example:
db:create("people", {friends={"name", "city", "notes"}, enemies={"name", "city", "notes"}})
This will create a database which contains two sheets: one named friends, the other named enemies. Each has three columns, name, city and notes-- and the datatype of each are strings, though the types are very flexible and can be changed basically whenever you would like. It’ll be stored in a file named Database_people.db in your Mudlet config directory on the hard drive should you want to share it.
It’s okay to run this function repeatedly, or to place it at the top-level of a script so that it gets run each time the script is saved: the DB package will not wipe out or clear the existing data in this case.
Note: You may not create a column or field name which begins with an underscore. This is strictly reserved to the db package for special use.
Note: Adding new columns to an existing database did not work in Mudlet 2.1 - see db:create() on how to deal with this.
Adding Data
To add data to your database, you must first obtain a reference (variable) for it. You do that with the db:get_database function, such as:
local mydb = db:get_database("people")
The database object contains certain convenience functions (discussed later, but all are preceded with an underscore), but also a reference to every sheet that currently exists within the database. You then use the db:add() function to add data to the specified sheet.
db:add(mydb.friends, {name="Ixokai", city="Magnagora"})
If you would like to add multiple rows at once to the same table, you can do that by just passing in multiple tables:
db:add(mydb.friends,
{name="Ixokai", city="Magnagora"},
{name="Vadi", city="New Celest"},
{name="Heiko", city="Hallifax", notes="The Boss"}
)
Notice that by default, all columns of every table are considered optional-- if you don’t include it in the add, then it will be set to its default value (which is nil by default)
For those familiar with databases: with the DB package, you don’t have to worry about committing or rolling back any changes, it will commit after each action automatically. If you would like more control than this, see Transactions below.
You also cannot control what is the primary key of any sheets managed with DB, nor do you have to create one. Each row will get a unique integer ID that automatically increments, and this field can be accessed as "_row_id".
Querying
Putting data in isn’t any fun if you can’t get it out. If you want every row from the sheet, you can do:
db:fetch(mydb.friends)
But rarely is that actually useful; usually you want to get only select data. For example, you only want to get people from the city of Magnagora. To do that you need to specify what criteria the system should use to determine what to return to you. It looks like this:
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"))
So the basic command is - db:fetch(_sheet_, _what to filter by_)
The following filter operations are defined:
db:eq(field, value[, case_insensitive]) -- Defaults to case insensitive, pass true as the last arg to
reverse this behavior.
db:not_eq(field, value[, case_insensitive) -- Not Equal To
db:lt(field, value) -- Less Than
db:lte(field, value) -- Less Than or Equal to.
db:gt(field, value) -- Greater Than
db:gte(field, value) -- Greater Than or Equal To
db:is_nil(field) -- If the column is nil
db:is_not_nil(field) -- If the column is not nil
db:like(field, pattern) -- A simple matching pattern. An underscore matches any single character,
and a percent(%) matches zero or more characters. Case insensitive.
db:not_like(field, pattern) -- As above, except it'll give you everything but what you ask for.
db:between(field, lower_bound, upper_bound) -- Tests if the field is between the given bounds (numbers only).
db:not_between(field, lower_bound, upper_bound) -- As above, only... not.
db:in_(field, table) -- Tests if the field is in the values of the table. NOTE the trailing underscore!
db:not_in(field, table) -- Tests if the field is NOT in the values of the table *
The db:in_ operator takes a little more explanation. Given a table, it tests if any of the values in the table are in the sheet. For example:
db:in_(mydb.friends.city, {"Magnagora", "New Celest"})
It tests if city == "Magnagora" OR city == "New Celest", but with a more concise syntax for longer lists of items.
There are also two logical operators:
db:AND(operation1, ..., operationN)
db:OR(operation1, operation2)
You may pass multiple operations to db:fetch in a table array, and they will be joined together with an AND by default. For example:
db:fetch(mydb.friends,
{db:eq(mydb.friends.city, "Magnagora"), db:like(mydb.friends.name, "X%")}
)
This will return every record in the sheet which is in the city of Magnagora, and has a name that starts with an X. Again note that in LIKE patterns, a percent is zero or more characters — this is the same effect as "X.*" in pcre patterns. Similarly, an underscore matches any single characters and so is the same as a dot in pcre.
Passing multiple expressions in an array to db:fetch is just a convenience, as its exactly the same as:
db:fetch(mydb.friends, db:AND(db:eq(mydb.friends.city, "Magnagora"), db:like(mydb.friends.name, "I%")))
The db:OR operation only takes two arguments, and will check to see if either of the two is true. You can nest these logical operators as deeply as you need to.
You can also just pass in a string directly to db:fetch, but you have to be very careful as this will be passed straight to the SQL layer. If you don’t know any SQL then you want to avoid this… for example, in SQL there’s a very big difference between double and single quotes. If you don’t know that, then stick to the db functions. But an example is:
db:fetch(mydb.friends, "city == 'Magnagora'")
Now, the return value of db:fetch() is always a table array that contains a table dictionary representing the full contents of all matching rows in the sheet. These are standard Lua tables, and you can perform all normal Lua operations on them. For example, to find out how many total items are contained in your results, you can simply do #results. If a request from the friends sheet were to return one row that you stored in the results variable, it would look like this if passed into the display() function:
table {
1: table {
'name': 'Bob',
'city': 'Magnagora',
'notes': 'Trademaster of Tailoring'
}
}
And if you were to echo(#results), it would show 1.
The order of the returned rows from db:fetch is generally the same as the order in which you entered them into the database, but no actual guarantees are made to this. If you care about the order then you can pass one or two optional parameters after the query to db:fetch() to control this.
The first table is an array of fields that indicate the column names to sort by; the second is a flag to switch from the default ascending(smallest to largest) sort, to a descending(largest to smallest) sort. For example:
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"), {mydb.friends.city})
This will return all your friends in Magnagora, sorted by their name, from smallest to largest. To reverse this, you would simply do:
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"), {mydb.friends.city}, true)
Including more then one field in the array will indicate that in the case that two rows have the same value, the second field should be used to sort them.
If you would like to return ALL rows from a sheet, but still sort them, you can do that by passing nil into the query portion. For example:
db:fetch(mydb.friends, nil, {mydb.friends.city, mydb.friends.name})
This will return every friend you have, sorted first by city and then their name.
Indexes and Types
The sheets we’ve defined thus far are very simple, but you can take more control over the process if you need to. For example, you may assign default values and types to columns, and the DB package will attempt to coerce them as appropriate. To do that, you change your db:create() call as:
db:create("people", {
friends={"name", "city", "notes"},
enemies={
name="",
city="",
notes="",
enemied="",
kills=0
}
})
This is almost the same as the original definition, but we’ve defined that our first four fields are strings with a default value of blank, and the new kills field which is an integer that starts off at 0. The only way to set a datatype is to set a default value at this time.
Please note, beneath the DB package is SQLite, and SQLite is very data-type neutral. It doesn’t really care very much if you break those rules and put an integer in a string field or vice-versa, but the DB package will — to a limited degree — attempt to convert as appropriate, especially for the operations that work on numbers.
You may also create both standard and unique indexes. A unique index enforces that a certain criteria can only happen once in the sheet. Now, before you go and make indexes, pause and consider. There is no right or wrong answer when it comes to what to index: it depends on what kind of queries you do regularly. If in doubt, don’t make an index. Indexes will speed up reading data from the sheet, but they will slow down writing data.
To add an index, pass either the _index or _unique keys in the table definition. An example:
db:create("people", {
friends={"name", "city", "notes"},
enemies={
name="",
city="",
notes="",
enemied="",
kills=0,
_index = { "city" },
_unique = { "name" }
}
})
Now, bear in mind: _index = { "name", "city"} creates two indexes in this sheet. One on the city field, one on the name field. But, _index = { {"name", "city"} } creates one index: on the combination of the two. Compound indexes help speed up queries which frequently scan two fields together, but don’t help if you scan one or the other.
The admonition against making indexes willy-nilly holds double for compound indexes: do it only if you really need to!
Uniqueness
As was specified, the _unique key can be used to create a unique index. This will make it so a table can only have one record which fulfills that index. If you use an index such as _unique = { "name" } then names must be unique in the sheet. You can specify more than one key to be unique; in that case they will be checked in an OR condition.
Now, if you use db:add() to insert a record which would violate the unique constraint, a hard error will be thrown which will stop your script. Sometimes that level of protection is too much, and in that case you can specify how the db layer handles violations.
There are three possible ways in which the layer can handle such violations; the default is to FAIL and error out.
You can also specify that the db layer should IGNORE any commands that would cause the unique constraint to be violated, or the new data should REPLACE the existing row.
For example:
db:add(mydb.enemies, {name="Bob", city="Sacramento"})
db:add(mydb.enemies, {name="Bob", city="San Francisco"})
With the name field being declared to be unique, these two commands can’t succeed normally. The first db:add() will create a record with the name of Bob, and the second would cause the uniqueness of the name field to be violated. With the default behavior (FAIL), the second db:add() call will raise an error and halt the script.
If you want the IGNORE behavior, the second command will not cause any errors and it will simply fail silently. Bob’s city will still be Sacramento.
With the REPLACE behavior, the second command will cause its data to completely overwrite and replace the first record. Bob’s city will now be San Francisco.
A word of caution with REPLACE, given:
db:add(mydb.enemies, {name="Bob", city="Sacramento", notes="This is something."})
db:add(mydb.enemies, {name="Bob", city="San Francisco"})
With the REPLACE behavior, the second record will overwrite the first-- but the second record does not have the notes field set. So Bob will now not have any notes. It doesn’t -just- replace existing fields with new ones, it replaces the entire record.
To specify which behavior the db layer should use, add a _violations key to the table definition:
db:create("people", {
friends={"name", "city", "notes"},
enemies={
name="",
city="",
notes="",
enemied="",
kills=0,
_index = { "city" },
_unique = { "name" },
_violations = "IGNORE"
}
})
Note that the _violations behavior is sheet-specific.
Timestamps
In addition to strings and floats, the db module also has basic support for timestamps. In the database itself this is recorded as an integer (seconds since 1970) called an epoch, but you can easily convert them to strings for display, or even time tables to use with Lua’s built-in time support.
The most common use for the Timestamp type is where you want the database to automatically record the current time whenever you insert a new row into a sheet. The following example illustrates that:
local mydb = db:create("combat_log",
{
kills = {
name = "",
area = "",
killed = db:Timestamp("CURRENT_TIMESTAMP"),
_index = { {"name", "killed"} }
}
}
)
-- observe that we don't provide the killed field here - DB automatically fills it in for us.
db:add(mydb.kills, {name="Drow", area="Undervault"})
results = db:fetch(mydb.kills)
display(results)
The result of that final display would show you this on a newly created sheet:
table {
1: table {
'_row_id': 1
'area': 'Undervault'
'name': 'Drow'
'killed': table {
'_timestamp': 1264317670
}
}
}
As you can see from this output, the killed fields contains a timestamp-- and that timestamp is stored as an epoch value in the GMT timezone. For your convenience, the db.Timestamp type offers three functions to get the value of the timestamp in easy formats. They are as_string
, as_number
and as_table
, and are called on the timestamp value itself.
The as_number function returns the epoch number, and the as_table function returns a time table. The as_string function returns a string representation of the timestamp, with a default format of "%m-%d-%Y %H:%M:%S". You can override this format to anything you would like. Details of what you can do with epoch values, time tables, and what format codes you can use are specified in the Lua manual at: http://www.lua.org/pil/22.1.html for the Lua date/time functions.
A quick example of the usage of these functions is:
results = db:fetch(mydb.kills)
for _, row in ipairs(results) do
echo("You killed " .. row.name .. " at: " .. (row.killed and row.killed:as_string() or "no time") .."\n")
end
Deleting
The db:delete function is used to delete rows from the sheet. It takes two arguments, the first being the sheet you are deleting and the second a query string built using the same functions used to build db:fetch() queries.
For example, to delete all your enemies in the city of Magnagora, you would do:
db:delete(mydb.enemies, db:eq(mydb.enemies.city, "Magnagora"))
Be careful in writing these! You may inadvertantly wipe out huge chunks of your sheets if you don’t have the query parameters set just to what you need them to be. Its advised that you first run a db:fetch() with those parameters to test out the results they return.
As a convenience, you may also pass in a result table that was previously retrieved via db:fetch and it will delete only that record from the table. For example, the following will get all of the enemies in Magnagora, and then delete the first one:
results = db:fetch(mydb.enemies, db:eq(mydb.enemies.city, "Magnagora"))
db:delete(mydb.enemies, db:eq(mydb.enemies._row_id, results[1]._row_id))
That is equivalent to:
db:delete(mydb.enemies, results[1])
You can even pass a number directly to db:delete if you know what _row_id you want to purge.
A final note of caution: if you want to delete all the records in a sheet, you can do so by only passing in the table reference. To try to protect you from doing this inadvertently, you must also pass true as the query after:
db:delete(mydb.enemies, true)
Updating
If you make a change to a table that you have received via db:fetch(), you can save those changes back to the database by doing:
db:update(mydb.enemies, results[1])
A more powerful (and somewhat dangerous, be careful!) function to make changes to the database is db:set, which is capable of making sweeping changes to a column in every row of a sheet. Beware, if you have previously obtained a table from db:fetch, that table will NOT represent this change.
The db:set() function takes two arguments: the field to change, the value to set it to, and the db:fetch() like query to indicate which rows should be affected. If you pass true as the last argument, ALL rows will be changed.
To clear out the notes of all of our friends in Magnagora, we could do:
db:set(mydb.friends.notes, "", db:eq(mydb.friends.notes, "Magnagora"))
Be careful in writing these!
Transactions
As was specified earlier, by default the db module commits everything immediately whenever you make a change. For power-users, if you would like to control transactions yourself, the following functions are provided on your database instance:
local mydb = db:get_database("my_database")
mydb:_begin()
mydb:_commit()
mydb:_rollback()
mydb:_end()
Once you issue a mydb._begin() command, autocommit mode will be turned off and stay off until you do a mydb._end(). Thus, if you want to always use transactions explicitly, just put a mydb._begin() right after your db:create() and that database will always be in manual commit mode.
Viewing and editing the database contents
A good tool to view and edit the database contents in raw form is SQlite Sorcerer (free and available for Linux, Windows, Mac).
Debugging raw queries
If you'd like to see the queries that db: is running for you, you can enable debug mode with db.debug_sql = true.
Discord Rich Presence
Discord Rich Presence in Mudlet allows you, the player, to show off the game you're playing and you, the game author, to get your game shown off! Advertise your game for free alongside AAA titles in server player lists :)
To respect the players privacy, this option is disabled by default - enable it by ticking the Discord option for the profile:
Once enabled, a Discord-capable game will show information in your Discord!
To fine-tune the information you'd like to see displayed, go to Settings, Chat tab:
Implementing
As a game author, you have two ways of adding Discord support to your game: via GMCP (easy) or via Lua.
Adding support via GMCP means that your players don't have to install any Lua scripts which is a nicer experience. To do so, implement the Discord over GMCP specification and get in touch to let us know your game implements GMCP.
GMCP
Here's a quick cheatsheet to implement the GMCP spec:
- Create a discord application
- Upload game logo for "rich presence invite image"
- Upload same game logo in "Rich Presence Assets" with the name of
server-icon
- Upon receiving "External.Discord.Hello" from the game client, reply with "External.Discord.Info" with
applicationid
(see screenshot) and "External.Discord.Status" - Send "External.Discord.Status" whenever you need to send data to the client, and fill it with the values have changed since the last status. Discord has some ideas for filling it in.
- Done. Mudlet will enable the Discord checkbox upon receiving the
applicationid
from the game at least once.
Lua
An alternative way to add Discord support as a game author is via Lua - all of Discords functionality can be manipulated from it. Create a discord application and set it with setDiscordApplicationID(), then set the set the rest of the options as necessary:
If you're a game player and your game doesn't support Discord, you can still use the functionality to set the detail, status, party and time information as desired.

MUD Client Media Protocol
Client.Media
Want to add accessibility and excitement into your game? How about implementing sound and music via GMCP?
The Client.Media family of GMCP packages provide a way for games to send sound and music events. GMCP media events are sent in one direction: from game server to to game client.
Client.Media in Mudlet
Media files may be downloaded manually or automatically if certain conditions are met.

Mudlet accepts case-insensitive GMCP for the Client.Media namespace (for example, these are all acceptable: "Client.Media.Play", "client.media.play", "cLiEnT.MeDiA.Play").
Enabling Media
When a new profile opens, Mudlet adds to the Core.Supports.Set GMCP package "Client.Media 1" to signal to servers that it supports processing media files via GMCP:
Core.Supports.Set ["Client.Media 1", ...]
To process Client.Media GMCP data in Mudlet, these boxes in the Settings window of Mudlet must be checked:
- The "Enable GMCP" box in the Miscellaneous section.
- The "Allow server to download and play media" box in the Game protocols section.
These boxes are checked by default upon the start of a new profile in Mudlet.
Storing Media
Mudlet plays files cached in the "media" folder within a game's profile. To get files into the "media" folder you could perform either of these options:
- Copy media files or extract them from an archive (zip)
- Automatically download them from external resources such as your game's web server on the Internet.
To enable the second option (Internet), use the "url" parameter made available in the "Client.Media.Default", "Client.Media.Load" and "Client.Media.Play" GMCP packages described below.
Loading Media
Send a Client.Media.Default GMCP event to setup the default URL directory to load sound or music files from external resources. This would typically be done once upon player login.
Required | Key | Value | Purpose |
---|---|---|---|
Yes | "url" | <url> |
|
For example, to setup the default URL directory for your game:
Client.Media.Default {
"url": "https://www.example.com/sounds/"
}
If downloading from external resources, it is recommended to use Client.Media.Default, set this default URL directory once, and let Mudlet download all of your media files automatically from this one resource location. Otherwise, explicitly set the "url" parameter on all of your Client.Media.Load GMCP and Client.Media.Play GMCP events to ensure that files are downloaded from the intended location(s).
Send Client.Media.Load GMCP events to load sound or music files. This could be done when the player logs into your game or at the beginning of a zone that will need the media.
Required | Key | Value | Purpose |
---|---|---|---|
Yes | "name" | <file name> |
|
Maybe | "url" | <url> |
|
For example, download the sound of a sword swooshing within the "media" folder:
Client.Media.Load {
"name": "sword1.wav",
"url": "https://www.example.com/sounds/"
}
Playing Media
Send Client.Media.Play GMCP events to play sound or music files.
Required | Key | Value | Default | Purpose |
---|---|---|---|---|
Yes | "name" | <file name> |
| |
Maybe | "url" | <url> |
| |
No | "type" | "sound" or "music" | "sound" |
|
No | "tag" | <tag> |
| |
No | "volume" | 1 to 100 | 50 |
|
No | "fadein" | <msec> |
| |
No | "fadeout" | <msec> |
| |
No | "start" | <msec> | 0 |
|
No | "loops" | -1, or >= 1 | 1 |
|
No | "priority" | 1 to 100 |
| |
No | "continue" | true or false | true |
|
No | "key" | <key> |
|
name
For example, to simply play the sound of a cow mooing already stored in the "media" folder:
Client.Media.Play {
"name": "cow.wav"
}
Or some lightning stored in a "weather" sub-folder under the "media" folder.
Client.Media.Play {
"name": "weather/lightning.wav"
}
The "name" parameter may be used for stopping media with the Client.Media.Stop GMCP event.
url
If you maintain your sound files on the Internet and don't set a default URL with Client.Media.Default, or preload them with Client.Media.Load, include the "url" parameter:
Client.Media.Play {
"name": "cow.wav",
"url": "https://www.example.com/sounds/"
}
type: sound
Media files default to a "type" of "sound" when the "type" parameter is not specified, such as in the example above. It is good practice to specify the "type" parameter to best keep media organized within your implementation:
Client.Media.Play {
"name": "cow.wav",
"type": "sound"
}
The "type" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.
tag
To play the sound of a sword swooshing and categorized as "combat":
Client.Media.Play {
"name": "sword1.wav",
"type": "sound",
"tag": "combat"
}
The "tag" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.
type: music
Add background music to your environment through use of the "music" value set upon the "type" parameter:
Client.Media.Play {
"name": "river.wav",
"type": "music",
"tag": "environment"
}
The "type" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.
volume: 1 to 100
As the character draws nearer to or farther from the environmental feature, consider adjusting the "volume" parameter. Example values, followed by syntax examples:
- Maximum: 100 (recommended to use rarely)
- High: 75
- Default: 50
- Low: 25
- Minimum: 1 (recommended to use rarely)
Client.Media.Play {
"name": "river.wav",
"type": "music",
"tag": "environment",
"volume": 75
}
Although using the integer type is recommended, Mudlet parses "volume" values of type string ("75") into integers (75) as needed.
fadein
Increase volume from the start of the media [start position, volume one] to the number in milliseconds specified with the "fadein" parameter [position start + milliseconds, volume specified with the "volume" parameter]. Example values, followed by syntax examples:
- 1000 milliseconds (1 second)
- 60000 milliseconds (1 minute)
- 0 milliseconds (no fade in)
Client.Media.Play {
"name": "monty_python.mp3",
"type": "music",
"volume": 100,
"fadein": 1000
}
+---------------------------+-----------------------+ | Fade in 1000 milliseconds | Normal | +---------------------------+-----------------------+ Volume 1|........::::::::::iiiiiiiii%%%%%%%%%%%%%%%%%%%%%%%%|Volume 100 +---------------------------+-----------------------+
Although using the integer type is recommended, Mudlet parses "fadein" values of type string ("1000") into integers (1000) as needed.
fadeout
Decrease volume from a position in milliseconds subtracted from the duration of the media [position duration - milliseconds, volume specified with the "volume" parameter] to the end of the media [position duration, volume one]. Example values, followed by syntax examples:
- 1000 milliseconds (1 second)
- 60000 milliseconds (1 minute)
- 0 milliseconds (no fade out)
Client.Media.Play {
"name": "the_matrix.mp3",
"type": "music",
"volume": 50,
"fadeout": 333
}
+-----------------------+---------------------------+ | Normal | Fade out 333 milliseconds | +-----------------------+---------------------------+ Volume 50|%%%%%%%%%%%%%%%%%%%%%%%%iiiiiiiii::::::::::........|Volume 1 +-----------------------+---------------------------+
Although using the integer type is recommended, Mudlet parses "fadeout" values of type string ("333") into integers (333) as needed.
start
Start playing a media track at the number of milliseconds specified. Example values, followed by syntax examples:
- 1000 milliseconds (1 second)
- 60000 milliseconds (1 minute)
- 0 milliseconds (start from beginning)
Client.Media.Play {
"name": "mudlet_beatboxing.mp3",
"type": "music",
"volume": 75,
"start": 1000
}
Although using the integer type is recommended, Mudlet parses "start" values of type string ("100") into integers (100) as needed.
loops: -1, 1 or more
The "loops" parameter controls how many times the sound repeats and defaults to 1 if not specified. A value of -1 will loop the file indefinitely.
Client.Media.Play {
"name": "clock/hour_bell.wav",
"type": "sound",
"loops": 3
}
Client.Media.Play {
"name": "underdark.mp3",
"type": "music",
"tag": "environment",
"loops": -1
}
Although using the integer type is recommended, Mudlet parses "loops" values of type string ("-1") into integers (-1) as needed.
priority: 1 to 100
The "priority" parameter sets precedence for Client.Media.Play GMCP events that include a "priority" setting. The values for the "priority" parameter range between 1 and 100. Given that two Client.Media.Play GMCP events have the same priority, the media already playing will continue playing. In Mudlet, media without priority set is not included comparisons based on priority.
A common place to find priority implemented is with combat. In the following example, imagine a combat scenario where some sounds of sword thrusts were interrupted by a successful blocking maneuver.
Client.Media.Play {
"name": "sword1.wav",
"type": "sound",
"tag": "combat",
"loops": 3,
"priority": 60
}
Client.Media.Play {
"name": "block1.wav",
"type": "sound",
"tag": "combat",
"priority": 70
}
Although using the integer type is recommended, Mudlet parses "priority" values of type string ("25") into integers (25) as needed.
The "priority" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.
continue: true or false (for music)
Typically sent with the "type" of "music" is the parameter "continue", which presents the following values:
- true: continues music that is already playing if it is requested again through a new Client.Media.Play GMCP event
- false: restarts music that is already playing if it is requested again through a new Client.Media.Play GMCP event
Client.Media.Play {
"name": "city.mp3",
"type": "music",
"tag": "environment",
"continue": true
}
If the "continue" parameter is not specified, behavior will default to true for music.
Although using the boolean type is recommended, Mudlet parses "continue" values of type string ("true" and "false") into boolean (true and false) as needed, as not all game drivers support a boolean type.
key
The "key" parameter enables media categorization, similar to the "tag" parameter, however it adds a feature of uniqueness that halts media currently playing with the same key, replacing it with the media that arrived from a new Client.Media.Play GMCP event. This update will only occur if the "name" or "url" associated with the currently playing media does not match the new media, while the key is identical.
In the example below, consider that a player moves from a sewer area to a village. The "key" parameter is used to stop the previously playing sewer.mp3 and start playing village.mp3 within the second Client.Media.Play GMCP event.
Client.Media.Play {
"name": "sewer.mp3",
"type": "music",
"tag": "environment",
"loops": -1,
"continue": true,
"key": "area-music"
}
Client.Media.Play {
"name": "village.mp3",
"type": "music",
"tag": "environment",
"loops": -1,
"continue": true,
"key": "area-music"
}
The "key" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.
Note: Where music is bound to change, continue or stop as a player enters a new room, consider allowing for a slight pause of 1 heart beat or tick to send the Client.Media.Play or Client.Media.Stop GMCP events. This practice reduces the number of Client.Media.Play GMCP events sent when the player travels through several rooms quickly.
randomization
Wildcards * (asterisk) and ? (question mark) may be used within the name to randomize media file(s) selection.
Given that media files underdark.wav, underdark.mp3 and underdark_dark_elven_moshpit.mp3 were all present in the media/environment directory under the current game profile, the following Client.Media.Play GMCP event would randomly choose one of those files to play using the * wildcard.
Client.Media.Play {
"name": "underdark*",
"type": "music",
"tag": "environment",
"loops": -1,
"continue": false
}
If media files sword1.wav, sword2.wav and sword3.wav were all present in the media/combat directory under the current game profile, the following Client.Media.Play GMCP event would randomly choose one of those files to play per each loop using the ? wildcard.
Client.Media.Play {
"name": "combat/sword?.wav",
"type": "sound",
"tag": "combat",
"loops": 3
}
Stopping Media
Send Client.Media.Stop GMCP events to stop sound or music media.
Required | Key | Value | Purpose |
---|---|---|---|
No | "name" | <file name> |
|
No | "type" | "sound" or "music" |
|
No | "tag" | <tag> |
|
No | "priority" | 1 to 100 |
|
No | "key" | <key> |
|
all
Send the Client.Media.Stop GMCP event with no parameters to stop all playing media within a given game profile.
Client.Media.Stop {}
parameters
Send any combination of the name, type, tag, priority or sound parameters and valid corresponding values to stop playing media that matches all combinations of the parameters.
Stop the rain.
Client.Media.Stop {
"name": "rain.wav"
}
Stop all media using the "type" of "sound".
Client.Media.Stop {
"type": "sound"
}
Stop all media categorized with the "tag" of "combat" and that has a "priority" less than or equal to 50.
Client.Media.Stop {
"tag": "combat",
"priority": 50
}
Stop all media categorized with the "key" of "area-music".
Client.Media.Stop {
"key": "area-music"
}
GUI Scripting in Mudlet
Mudlet has extremely powerful GUI capabilities built into it, and with the inclusion of the Geyser and Vyzors layout managers in Mudlet's Lua API it is quicker and easier to get a basic UI created.
Geyser
Geyser is an object oriented framework for creating, updating and organizing GUI elements within Mudlet - it allows you to make your UI easier on Mudlet, and makes it easier for the UI to be compatible with different screen sizes.
Geyser's manual is quite extensive - follow here to read up on it.
UI template
Akaya has created a UI template based on Geyser that can serve as a quick start for customizing the Mudlet interface to your character:
To get started with it, see the forum thread about Geyser UI Template.
Simple Window Manager
Simple Window Manager is a light-weight script designed to provide the GUI object placement and sizing functionality seen in Geyser and Vyzor without any of the extras. Any GUI object, once created normally, can be added to the SWM along with a corner to base its positioning info off of, the distance from that corner, and the size of the object in any combination of pixels and percentages of the screen. SWM does all the behind the scenes work to keep all objects it has been given to manage in their correct places and sizes as the screen changes size. All other interactions with GUI objects are handled using standard functions built into Mudlet.
Simple Window Managers manual, and download, can be found here.
Useful Resources
There are several useful resources you can refer to when creating your GUI.
- Wiki Resources
- Excellent for getting an initial feel of how to use the Geyser layout manager.
- The GUI section of the Lua API manual
- External Resources
- The Geyser Layout Manager subforum on Mudlet's forums.
- A pinned thread on Mudlet's forums for showing what your GUI looks like. Useful for ideas and to see what is possible.
- A forum thread which follows the evolution of the UI provided by God Wars II
Resetting your UI
While scripting your UI, you can reset it completely and have your scripts be loaded from scratch with the resetProfile() function - in the input line, type lua resetProfile()
.
Best Practices
- The hope is that this page will provide a place to collect a list of Mudlet 'best practices' in an effort to help people keep their Mudlet scripts and packages clean, efficient, and running smoothly. Another way to think of it is a collection of tips and tricks for making Mudlet run its best. They largely fall under these categories.
- Lua best practices
- Since Lua is the scripting language Mudlet makes use of, the majority of the best practices for Lua will apply when writing Mudlet scripts.
- We do not aim to replace the internet as a source of Lua knowledge, but will try to highlight the most beneficial ones
- Potential exceptions will be noted with their entries
- GUI best practices
- keeping your UI looking it best in as many situations as possible
- Mudlet best practices
- Optimizations and items specific to Mudlet's triggers, aliases, API, etc
- Generic mapper best practices
Lua
Use local variables
You should really be using local variables wherever you can. If a variable is only needed for the duration of a function, alias, or trigger, then make it a local every time. If you will need to access it repeatedly in your script, make it local first. Always be asking yourself, "Could I be using a local instead?"
-- bad
function myEcho(msg)
transformed_msg = "<cyan>(<yellow>Highlighter<cyan>)<reset>" .. msg
cecho(transformed_msg)
end
-- better
function myEcho(msg)
local transformed_msg = "<cyan>(<yellow>Highlighter<cyan>)<reset>" .. msg
cecho(transformed_msg)
end
There are three main reasons for doing so:
- Making things local keeps them from colliding with variables in use by other package developers. You are probably not the first person to use "tbl" for a temporary table name.
- You can make the code easier to both read and write.
self.mc[tabName]
is a bit much to type and remember, but if you first dolocal console = self.mc[tabName]
then it's obvious you're referring to a console where you use it in future
- It's faster:
- local variables are inherently faster in Lua, as they exist in the virtual machine registers and are a simple index lookup to access, whereas globals reside in a table and are therefore a hash lookup
- this means you can increase the speed of intensive processes just by making functions and variables local before using them.
- For instance, if you are going to cycle through a large table and cecho items from within it, adding
local cecho = cecho
above the loop can improve performance.
- local variables are inherently faster in Lua, as they exist in the virtual machine registers and are a simple index lookup to access, whereas globals reside in a table and are therefore a hash lookup
Conversely, avoid _G when possible
It's not only good practice to use local variables where possible, but you should avoid referencing the global table, _G. The very thing which makes _G useful (being able to reference elements if you don't know their name before hand) is what makes it dangerous, as it can be easy to overwrite things you shouldn't and leave yourself in a broken state. For instance, all it takes is accidentally writing to _G["send"] and suddenly all of your scripts which send commands to the game are broken.
Get into a habit of using a namespace for your scripts instead - see below.
Avoid overwriting your variables accidentally
Often times you need to initialize your tables at the top of your scripts. But if you click on that script again later and back off it will save and overwrite your current data. You can use 'or' to avoid this as shown below.
-- have to make a table before you can add things to it
-- risks overwriting the entire table if I resave the script
demonnic = {}
-- if the variable has already been defined, it is just set back to itself. If it has not, then it's set to a new table
demonnic = demonnic or {}
Ternary statements in Lua (set a variable based on a condition)
Lua does not have a ternary operator as such, but you can construct a statement in such a way it functions as one, allowing for shorter and more readable code. For example:
-- you can rewrite this if statement
if something then
myVariable = "x"
else
myVariable = "y"
end
-- as
myVariable = something and "x" or "y"
Group your globals together in a table
Sometimes you have to use globals, to pass values easily between items or make functions and values available to others. Lots of package makers may have a reason to track health and want to be able to pass it easily between triggers and functions without having to make it a parameter for every function they write. Obviously they can't all use the 'health' variable though, especially if one is using percentages and the other direct values. So it's best if you keep the variables for your package grouped together within a table. "Demonnic.health" is a lot less likely to collide than just 'health' There is a forum post with more information.
Declaring functions in tables: myTable:function() vs myTable.function()
Lua does not have as much syntactic sugar as some other languages, but using a : to call a function within a table is one of them. The following declarations are functionally identical
function myTable:coolFunction(parameter)
self.thing = parameter
end
function myTable.coolFunction(self, parameter)
self.thing = parameter
end
myTable.coolFunction = function(self, parameter)
self.thing = parameter
end
And these calls are equivalent
myTable:coolFunction("Test")
myTable.coolFunction(myTable, "Test")
You can use this to make it easier to keep your code self-contained and grouped together. You can combine it with setmetatable() to allow a sort of Object Oriented like programming pattern. Which leads us to
Create objects and 'classes' using metatables and:
Geyser makes extensive use of this pattern and it allows you to create classes and objects within Lua's procedural environment. The chapter in Programming in Lua on Object Oriented Programming does a good job of explaining it.
GUI
Give your Geyser elements unique names
While Geyser will generate a name for you if you do not provide one, if you do provide one it gives you some measure of protection against accidental duplication, as miniconsoles and labels with the same name are reused. Likewise, you should make sure you use names which are unlikely to be used by anyone else. "healthgauge" or "container" are maybe a little generic. Try "my_package_name_health_gauge" or similar. It's more typing up front, but you shouldn't need to type it again and it will help a lot in ensuring your UI behaves as expected.
Use percentages
A lot of your users will be on different resolution monitors, or may not want to have Mudlet covering their entire screen. If you hardcode your sizes as direct pixel values for your Geyser objects, they will not scale as well when the window is resized due to resolution restrictions or user preference. If you're personally working on a 1080p resolution UI but you want it to scale up or down, rather than using "640px" as the width to cover a third of the screen use "33%" for the width, and it will resize to cover a third of the window no matter the size.
Adjustable Containers put the power back in your user's hands
If you use Adjustable.Container for groupings of your UI it allows your users to resize and move them around if they don't like the way you've arranged things. This means more people using your package in the end.
Mudlet
Shield your complicated regular expression triggers with a substring trigger
- Regular expressions are very useful, but are one of the slower trigger types to process for Mudlet. Using a substring trigger gate or a multiline trigger with the substring trigger ahead of the regular expression and a line delta of 0 you can reduce the processing time of your triggers overall by quite a bit. There has been benchmarking done
Avoid expandAlias()
where possible
- There's a whole wiki page on this at Functions_vs_expandAlias
feedTriggers is for testing, not production
- the c/d/h/feedTriggers functions are great for testing your triggers without having to make something actually happen in your game. But you should not be using it as a functional part of your system. Much like with expandAlias, you should be calling a function from the trigger and the place you are calling feedTriggers to do the same thing, rather than getting the trigger engine itself involved.
Capture the IDs returned by your temp items and anonymous event handlers
- You can now skip the following by using registerNamedEventHandler or registerNamedTimer instead. The below still holds true if you want to use the anonymous functions directly and is left for that reason.
- One of the more common issues people come into the help channel with is stacking tempTimers and old anonymous event handlers which have been edited not being cleared out and still firing. The solution for these issues is the same. The functions which create temporary or anonymous items in Mudlet return an ID. You need to save this ID to a variable and use it to remove the existing item before reregistering it. So for examples
-- incorrect, can stack timers
tempTimer(0.5, function()
send("And another one")
end)
-- Ensures the timer only fires once, .5 seconds after the first time it is called
if not myTempTimerID then -- only do something if we haven't already
myTempTimerID = tempTimer(0.5, function()
send("Only one")
myTempTimerID = nil -- unset it so it can fire again
end)
end
-- Resets the tempTimer each time it is run, so it runs
if myTempTimerID then
killTimer(myTempTimerID) -- can run killTimer on an already fired timer without causing an issue.
end
myTempTimerID = tempTimer(0.5, function()
send("Only one")
end)
Package and Module best practices
- This is a list of things we have discovered over the years leads to the best user experience with Mudlet packages. They aren't all necessary, but you will find that the more of them you do, the easier the lives of your users and ultimately yourself.
- built-in auto-updates
- so players stay up to date, which will not be the case with manual updates)
- modular and extendable - use Mudlet modules for this
- so people can disable ones not needed)
- event based - raise events of your own for others to hook into
- so the order of scripts installed in the players profile doesn't matter
- make sure aliases only call functions
- so people can make their own aliases or keybindings to customize as needed without using expandAlias
- don't pollute the global namespace, keep everything in a table
- so you don't bugs from people overwriting it or vice versa)
- touched on above but bears repeating
- undo any UI changes on uninstall: set borders back, hide the UI, etc
- so people have a good experience even if they didn't like the package
- if you're specifying any fonts, package them
- while it might be available on your computer, not guaranteed to be available on every computer
- if you're a game admin, install it automatically via GMCP
- less overhead for players to get a good experience
- if you're a game admin, provide GMCP data for your game
- so people don't have to waste time trying to capture data, and can work with it instead
- don't use \ in paths, use / - even for Windows
- it'll work on Windows - and work on macOS and Linux too
Generic Mapper
- when adding customisation triggers to the generic mapper, add them outside of the
generic_mapper
folder- this is so when the mapper updates, you keep your changes
Here you can find a long list of all possible Lua functions and programming interfaces (API) that Mudlet offers. Due to the integrated Lua, you can also use all regular Lua functions. In the following page, we will explain the usage, expected behavior and examples for the functions added in Mudlet.
Global variables
Mudlet defines several global Lua variables that are accessible from anywhere.
Built-in Lua Variables | |||||
---|---|---|---|---|---|
Variable Name | Description | ||||
command
|
This variable holds the current user command, i.e. unchanged by any aliases or triggers. This is typically used in alias scripts. | ||||
line
|
This variable holds the content of the current line as being processed by the trigger engine. The engine runs all triggers on each line as it arrives from the game. | ||||
matches[n]
|
This Lua table is being used by Mudlet in the context of triggers that use Perl regular expressions.
matches[1] holds the entire match, matches[2] holds the first capture group, matches[n] holds the nth-1 capture group. If the Perl trigger indicated 'match all' (same effect as the Perl /g switch) to evaluate all possible matches of the given regex within the current line, matches[n+1] will hold the second entire match, matches[n+2] the first capture group of the second match and matches[n+m] the m-th capture group of the second match. Since Mudlet 4.11+ it will contain named capturing groups, apart from numeric group matches (named groups count as numeric as well). Each can be access under element with key corresponding to group name.
Eg. if you capture group with name | ||||
multimatches[n][m]
|
This table is being used by Mudlet in the context of multiline triggers that use Perl regular expression. It holds the table matches[n] as described above for each Perl regular expression based condition of the multiline trigger. multimatches[5][4] may hold the 3rd capture group of the 5th regex in the multiline trigger. This way you can examine and process all relevant data within a single script. | ||||
mudlet.translations
|
Contains translations of some common texts (right now, exit directions only) that are helpful to you in Lua scripting, as well as the current language selected for the user interface. - See translateTable() | ||||
mudlet.key
|
Makes your life easier when creating new keybindings via Lua by translating the key name into the number needed - see tempKey(). | ||||
mudlet.keymodifier
|
Same as mudlet.key , but for keyboard modifiers - Ctrl, Alt, etc.
| ||||
mudlet.supports
|
Lists special functionality that the users Mudlet supports - right now, just mudlet.supports.coroutines & mudlet.supports.namedGroups is listed. Use mudlet.supports to conditionally enable functionality as it's available on the users Mudlet.
| ||||
color_table
|
Color definitions used by Geyser, cecho, and many other functions - see showColors(). The profile's color preferences are also accessible under the ansi_ keys.
|
There are other variables that hold the game's MUD-protocol data that are global as well - see Supported Protocols.
Function Categories
Basic Essential Functions: These functions are generic functions used in normal scripting. These deal with mainly everyday things, like sending stuff and echoing to the screen.
Database Functions: A collection of functions for helping deal with the database.
Date/Time Functions: A collection of functions for handling date & time.
File System Functions: A collection of functions for interacting with the file system.
Mapper Functions: A collection of functions that manipulate the mapper and its related features.
Miscellaneous Functions: Miscellaneous functions.
Scripting Object Functions: A collection of arrows that manipulate Mudlets scripting objects - triggers, aliases, and so forth.
Networking Functions: A collection of functions for managing networking.
String Functions: These functions are used to manipulate strings.
Table Functions: These functions are used to manipulate tables. Through them you can add to tables, remove values, check if a value is present in the table, check the size of a table, and more.
Text to Speech Functions: These functions are used to create sound from written words. Check out our Text-To-Speech Manual for more detail on how this all works together.
UI Functions: These functions are used to construct custom user GUIs. They deal mainly with miniconsole/label/gauge creation and manipulation as well as displaying or formatting information on the screen.
Discord Functions: These functions are used to customize the information Mudlet displays in Discord's rich presence interface. For an overview on how all of these functions tie in together, see our Discord scripting overview.
Additionally, more advanced functions are available in the Lua 5.1 manual.
Basic Essentials
These functions are generic functions used in normal scripting. These deal with mainly everyday things, like sending stuff and echoing to the screen.
debugc
- debugc(content)
- Again this will not send anything to anywhere. It will however print not to the main window, but only to the errors view. You need to open that window to see the message.
- See also: Errors View
Note: Do not use this to display information to end-users. It will be hard to find. It is mainly useful for developing/debugging. Does not echo to the debug window
debugc(" Trigger successful!")
-- Text will be shown in errors view, not to main window.
display
- display(content)
- This is much like echo, in that is will show text at your screen, not send anything to anywhere. However, it also works with other objects than just text, like a number, table, function, or even many arguments at once. This function is useful to easily take a look at the values of a lua table, for example. If a value is a string of letters, it'll be in quotes, and if it's a number, it won't be quoted.
Note: Do not use this to display information to end-users. It may be hard to read. It is mainly useful for developing/debugging.
myTable = {} -- create an empty lua table
myTable.foo = "Hello there" -- add a text
myTable.bar = 23 -- add a number
myTable.ubar = function () echo("OK") end -- add more stuff
display( myTable ) -- take a look inside the table
echo
- echo([miniconsoleName or labelName], text)
- This function appends text at the end of the current line.
- Parameters
- miniconsoleName: (optional) the miniconsole to echo to, or:
- labelName: (optional) the label to echo to.
- text: text you'd like to see printed. You can use \n in an echo to insert a new line. If you're echoing this to a label, you can also use styling to color, center, increase/decrease size of text and various other formatting options as listed here.
See also: moveCursor(), insertText(), cecho(), decho(), hecho()
As of Mudlet 4.8+, a single line is capped to 10,000 characters (this is when ~200 at most will fit on one line on your screen).
- Example
-- a miniconsole example
-- first, determine the size of your screen
local windowWidth, windowHeight = getMainWindowSize()
-- create the miniconsole
createMiniConsole("sys", windowWidth-650,0,650,300)
setBackgroundColor("sys",255,69,0,255)
setMiniConsoleFontSize("sys", 8)
-- wrap lines in window "sys" at 40 characters per line - somewhere halfway, as an example
setWindowWrap("sys", 40)
echo("sys","Hello world!\n")
cecho("sys", "<:OrangeRed>This is random spam with the same background\n")
cecho("sys", "<blue:OrangeRed>and this is with a blue foreground. ")
cecho("sys", "<bisque:BlueViolet>Lastly, this is with both a foreground and a background.\n")
-- a label example
-- This example creates a transparent overlay message box to show a big warning message "You are under attack!" in the middle
-- of the screen. Because the background color has a transparency level of 150 (0-255, with 0 being completely transparent
-- and 255 opaque) the background text can still be read through.
local width, height = getMainWindowSize()
createLabel("messageBox",(width/2)-300,(height/2)-100,250,150,1)
resizeWindow("messageBox",500,70)
moveWindow("messageBox", (width/2)-300,(height/2)-100 )
setBackgroundColor("messageBox", 255, 204, 0, 200)
echo("messageBox", [[<p style="font-size:35px"><b><center><font color="red">You are under attack!</font></center></b></p>]])
printDebug
- printDebug(msg, [showStackTrace])
- Prints a debug message in green to the error console in the script editor only. Does not echo to the debug window or the main console. Includes stack trace if showStackTrace is included and not nil or false.
- See also
- printError, debugc

Note: This will not be echoed to the main console even if the option to echo Lua errors to the main console is turned on. Does not echo to the debug window. As such you can use it for debugging information without fear it will be shown unless someone goes looking for errors.
- Parameters
- msg:
- string to echo to the error console
- showStackTrace:
- (optional) boolean true if you want to include the stack trace, leave off if you do not.
- Example
-- print a debug message to the error console for troubleshooting purposes, when you don't want to echo the information to the main screen.
-- the only difference between this and debugc is this includes information on the script/alias/trigger/etc and line it was called from, whereas debugc does not.
printDebug("Switching to chaos mode")
-- Want to record that something occurred, and include stacktrace so you can see what path the code was taking, but you don't want to halt execution or have it show up in main screen or in scary red.
printDebug("Something unexpected occurred but we can recover from it. Still, we want to be able to notice and troubleshoot it with extra information.", true)
printError
- printError(msg, [showStackTrace], [haltExecution])
- Prints an error message in red to the error console in the script editor. Can optionally include stacktrace information and halt execution.
- See also
- printDebug, debugc

Note: This WILL be echoed to the main console if the option to echo Lua errors to the main console is turned on. You should not use this for idle debugging information, but actual errors that may put big red error lines in the main window.
- Parameters
- msg:
- string to echo to the error console
- showStackTrace:
- (optional) true if you want to include the stack trace, leave off if you do not.
- haltExecution:
- (optional) true if you want to halt execution. You must pass a value for showStackTrace in order to halt execution.
- Example
-- print an error message but do not include extra stack information or halt execution.
-- this is similar to debugc except it include more information on the place it was called from
-- and will show up in red and echo to the main console if the option for errors to echo there is selected.
printError("Your maxhp is below your currenthp and our game doesn't allow for that. HAX?!")
-- Something bad happened, for sure, but your script can recover.
-- Make sure this is something important enough it might make it to the main window as a big red error.
-- but we are not halting execution, since we can carry on in some capacity
printError("gmcp values for this thing went missing, will carry on using defaults but you should tell somebody about this.", true)
-- print an error message to the error console for troubleshooting purposes.
-- Prints stack trace for troubleshooting and halts execution (because you cannot continue without the configuration, presumably)
-- similar to using error(msg) but includes the stacktrace information.
printError("Our entire configuration seems to have gone missing!", true, true)
send
- send(command, showOnScreen)
- This sends "command" directly to the network layer, skipping the alias matching. The optional second argument of type boolean (print) determines if the outgoing command is to be echoed on the screen.
See also: sendAll(), speedwalk()
Note: If you want your command to be checked as if it's an alias, use expandAlias() instead - send() will ignore them.
send("Hello Jane") --echos the command on the screen
send("Hello Jane", true) --echos the command on the screen
send("Hello Jane", false) --does not echo the command on the screen
-- use a variable in the send:
send("kick "..target)
-- to send directions:
speedwalk("s;s;w;w;w;w;w;w;w;")
-- to send many things:
sendAll("hi", "open door e", "e", "get item", "sit")
Note: The game server can choose not to show commands sent on screen (for example, if you're typing in a password).
Database Functions
These database functions make using a database with Mudlet easier. They are in addition to the LuaSQL sqlite driver that's available directly within Mudlet (also see the LuaSQL manual for comparison).
For a tutorial on how to get started with the database functions, see here.
db:add
- db:add(sheet reference, table1, …, tableN)
- Adds one or more new rows to the specified sheet. If any of these rows would violate a UNIQUE index, a lua error will be thrown and execution will cancel. As such it is advisable that if you use a UNIQUE index, you test those values before you attempt to insert a new row.
- Returns nil plus the error message if the operation failed (so it won't raise a runtime error in Mudlet).
- Example
--Each table is a series of key-value pairs to set the values of the sheet,
--but if any keys do not exist then they will be set to nil or the default value.
db:add(mydb.enemies, {name="Bob Smith", city="San Francisco"})
db:add(mydb.enemies,
{name="John Smith", city="San Francisco"},
{name="Jane Smith", city="San Francisco"},
{name="Richard Clark"})
--As you can see, all fields are optional.
-- example that'll show an error if things went wrong:
local ok, err = db:add(mydb.enemies, {name="Bob Smith", city="San Francisco"})
if not ok then
debugc(f"Error adding to the database: {err}")
return
end
db:aggregate
- db:aggregate(field reference, aggregate function, query, distinct)
- Returns the result of calling the specified aggregate function on the field and its sheet. The query is optional.
- The supported aggregate functions are:
- COUNT - Returns the total number of records that are in the sheet or match the query.
- AVG - Returns the average of all the numbers in the specified field.
- MAX - Returns the highest number in the specified field.
- MIN - Returns the lowest number in the specified field.
- TOTAL - Returns the value of adding all the contents of the specified field.
Note: You can supply a boolean true for the distinct argument since Mudlet 3.0 to filter by distinct values.
- Example
local mydb = db:get_database("my database")
echo(db:aggregate(mydb.enemies.name, "count"))
- It can also be used in conjunction with db:like to return a number of results.
- Example
local query = matches[2]
local mydb = db:get_database("itemsdab")
local results = db:aggregate(mydb.itemstats.objname, "count", db:like(mydb.itemstats.objname, "%" .. query .. "%"))
cecho("Found <red>"..results.."<reset> items that match the description.")
db:AND
- db:AND(sub-expression1, …, sub-expressionN)
- Returns a compound database expression that combines all of the simple expressions passed into it; these expressions should be generated with other db: functions such as db:eq, db:like, db:lt and the like.
- This compound expression will only find items in the sheet if all sub-expressions match.
db:between
- db:between(field reference, lower_bound, upper_bound)
- Returns a database expression to test if the field in the sheet is a value between lower_bound and upper_bound. This only really makes sense for numbers and Timestamps.
db:close
- db:close(database name)
- Closes a database connection so it can't be used anymore.
db:create
- db:create(database name, schema table, force)
- Creates and/or modifies an existing database. This function is safe to define at a top-level of a Mudlet script: in fact it is recommended you run this function at a top-level without any kind of guards. If the named database does not exist it will create it. If the database does exist then it will add any columns or indexes which didn’t exist before to that database. If the database already has all the specified columns and indexes, it will do nothing. If an existing column with at least one non-NULL value is missing from the new schema, it will raise an error by default; the user may force the dropping of the column by setting the force argument to true.
- The database will be called Database_<sanitized database name>.db and will be stored in the Mudlet configuration directory within your profile folder, which you can find with getMudletHomeDir().
- Database tables are called sheets consistently throughout this documentation, to avoid confusion with Lua tables.
- The schema table must be a Lua table array containing table dictionaries that define the structure and layout of each sheet. The starting Lua type will determine the type in the database, i.e. if you want to store text set it to
= ""
and if you want to store a number set it to= 0
.
- Example
local mydb = db:create("combat_log",
{
kills = {
name = "",
area = "",
killed = db:Timestamp("CURRENT_TIMESTAMP"),
damage = 0,
_index = { {"name", "area"} }
},
enemies = {
name = "",
city = "",
reason = "",
enemied = db:Timestamp("CURRENT_TIMESTAMP"),
_index = { "city" },
_unique = { "name" },
_violations = "IGNORE"
}
})
- The above will create a database with two sheets; the first is kills and is used to track every successful kill, with both where and when the kill happened. It has one index, a compound index tracking the combination of name and area. The second sheet has two indexes, but one is unique: it isn’t possible to add two items to the enemies sheet with the same name.
- For sheets with unique indexes, you may specify a
_violations
key to indicate how the db layer handle cases where the data is duplicate (unique index is violated). The options you may use are:
- FAIL - the default. A hard error is thrown, cancelling the script.
- IGNORE - The command that would add a record that violates uniqueness just fails silently.
- REPLACE - The old record which matched the unique index is dropped, and the new one is added to replace it.
- Returns a reference of an already existing database. This instance can be used to get references to the sheets (and from there, fields) that are defined within the database. You use these references to construct queries.
- If a database has a sheet named enemies, you can obtain a reference to that sheet by doing:
local mydb = db:get_database("my database")
local enemies_ref = mydb.enemieslocal
local name_ref = mydb.enemies.name
Note: db:create() supports adding new columns and indexes to existing databases, but this functionality was broken in Mudlet 2.1 due to the underlying Lua SQL binding used being out of date. When you want to add a new column, you have several options:
- if you are just testing and getting setup, close Mudlet, and delete the Database_<sanitized database name>.db file in your Mudlet folder.
- if you've already gotten a script and have a fair bit of data with it, or users are already using your script and telling them to delete files on an upgrade is unreasonable, you can use direct SQL to add in a new column. WARNING, this is an expert option, and requires knowledge of SQL to accomplish. You must backup your database file before you start coding this in.
-- at first, update your db:create schema to have the new field.
-- then, we'll tell the database to create it if it doesn't exist
-- fetch the data we've got in our sample database
local test = db:fetch(ndb.db.people)
-- this requires at least one entry in the database to work
if next(test) then
local _,someperson = next(test)
-- in this example, we want to add an order key. If there is no key, means it doesn't exist yet, so it should be added.
if someperson.order == nil then
-- do not do the things you see here elsewhere else. This is a big hack/workaround.
local conn = db.__conn.namedb
-- order should be a text field, so note that we specify it's type with TEXT and the default value at the end with ""
local sql_add = [[ALTER TABLE people ADD COLUMN "order" TEXT NULL DEFAULT ""]]
conn:execute(sql_add)
conn:commit()
end
-- here is an another example, in one where we need to add a field that is a number
if someperson.dragon == nil then
local conn = db.__conn.namedb
-- observe that we use the REAL type by default instead and a default of 0
local sql_add = [[ALTER TABLE people ADD COLUMN "dragon" REAL NULL DEFAULT 0]]
conn:execute(sql_add)
conn:commit()
end
end
db:delete
- db:delete(sheet reference, query)
- Deletes rows from the specified sheet. The argument for query tries to be intelligent:
- If it is a simple number, it deletes a specific row by _row_id
- If it is a table that contains a _row_id (e.g., a table returned by db:get) it deletes just that record.
- Otherwise, it deletes every record which matches the query pattern which is specified as with b:get.
- If the query is simply true, then it will truncate the entire contents of the sheet.
- Example
enemies = db:fetch(mydb.enemies)
db:delete(mydb.enemies, enemies[1])
db:delete(mydb.enemies, enemies[1]._row_id)
db:delete(mydb.enemies, 5)
db:delete(mydb.enemies, db:eq(mydb.enemies.city, "San Francisco"))
db:delete(mydb.enemies, true)
- Those deletion commands will do in order:
- one When passed an actual result table that was obtained from db:fetch, it will delete the record for that table.
- two When passed a number, will delete the record for that _row_id. This example shows getting the row id from a table.
- three As above, but this example just passes in the row id directly.
- four Here, we will delete anything which matches the same kind of query as db:fetch uses-- namely, anyone who is in the city of San Francisco.
- five And finally, we will delete the entire contents of the enemies table.
db:eq
- db:eq(field reference, value)
- Returns a database expression to test if the field in the sheet is equal to the value.
db:exp
- db:exp(string)
- Returns the string as-is to the database.
- Use this function with caution, but it is very useful in some circumstances. One of the most common of such is incrementing an existing field in a db:set() operation, as so:
db:set(mydb.enemies, db:exp("kills + 1"), db:eq(mydb.enemies.name, "Ixokai"))
- This will increment the value of the kills field for the row identified by the name Ixokai.
- But there are other uses, as the underlining database layer provides many functions you can call to do certain things. If you want to get a list of all your enemies who have a name longer then 10 characters, you may do:
db:fetch(mydb.enemies, db:exp("length(name) > 10"))
- Again, take special care with this, as you are doing SQL syntax directly and the library can’t help you get things right.
db:fetch
- db:fetch(sheet reference, query, order_by, descending)
- Returns a table array containing a table for each matching row in the specified sheet. All arguments but sheet are optional. If query is nil, the entire contents of the sheet will be returned.
- Query is a string which should be built by calling the various db: expression functions, such as db:eq, db:AND, and such. You may pass a SQL WHERE clause here if you wish, but doing so is very dangerous. If you don’t know SQL well, its best to build the expression.
- Query may also be a table array of such expressions, if so they will be AND’d together implicitly.
- The results that are returned are not in any guaranteed order, though they are usually the same order as the records were inserted. If you want to rely on the order in any way, you must pass a value to the order_by field. This must be a table array listing the fields you want to sort by. It can be { mydb.kills.area }, or { mydb.kills.area, mydb.kills.name }
- The results are returned in ascending (smallest to largest) order; to reverse this pass true into the final field.
- Example
db:fetch(mydb.enemies, nil, {mydb.enemies.city, mydb.enemies.name})
db:fetch(mydb.enemies, db:eq(mydb.enemies.city, "San Francisco"))
db:fetch(mydb.kills,
{db:eq(mydb.kills.area, "Undervault"),
db:like(mydb.kills.name, "%Drow%")}
)
- The first will fetch all of your enemies, sorted first by the city they reside in and then by their name.
- The second will fetch only the enemies which are in San Francisco.
- The third will fetch all the things you’ve killed in Undervault which have Drow in their name.
db:fetch_sql
- db:fetch_sql(sheet reference, sql string)
- Allows to run db:fetch with hand crafted sql statements.
- When you have a large number of objects in your database, you may want an alternative method of accessing them. In this case, you can first obtain a list of the _row_id for the objects that match your query with the following alias:
- Example
local mydb = db:get_database("itemsdab")
local query = matches[2]
local t = {}
res = db:fetch(mydb.itemstats, db:query_by_example(mydb.itemstats, {objname = "%" .. query .. "%"}))
for k, v in pairs(res) do
print(v._row_id)
table.insert(t,v._row_id)
end
handoff = table.concat(t, "|")
display(handoff)
- Then you can use the following code in a separate alias to query your database using the previously retrieved _row_id.
- Example
local mydb = db:get_database("itemsdab")
local query = matches[2]
display(db:fetch_sql(mydb.itemstats, "select * from itemstats where _row_id ="..query))
--This alias is used to query a database by _row_id
db:gt
- db:gt(field reference, value)
- Returns a database expression to test if the field in the sheet is greater than to the value.
db:get_database
- db:get_database(database_name)
- Returns your database name.
- Example
local mydb = db:get_database("my database")
db:gte
- db:gte(field reference, value)
- Returns a database expression to test if the field in the sheet is greater than or equal to the value.
db:in_
- db:in_(field reference, table array)
- Returns a database expression to test if the field in the sheet is one of the values in the table array.
- First, note the trailing underscore carefully! It is required.
- The following example illustrates the use of in_:
local mydb = db:get_database("my database")
local areas = {"Undervault", "Hell", "Purgatory"}
db:fetch(mydb.kills, db:in_(mydb.kills.area, areas))
- This will obtain all of your kills which happened in the Undervault, Hell or Purgatory. Every db:in_ expression can be written as a db:OR, but that quite often gets very complex.
db:is_nil
- db:is_nil(field reference)
- Returns a database expression to test if the field in the sheet is nil.
db:is_not_nil
- db:is_not_nil(field reference)
- Returns a database expression to test if the field in the sheet is not nil.
db:like
- db:like(field reference, pattern)
- returns a database expression to test if the field in the sheet matches the specified pattern.
- LIKE patterns are not case-sensitive, and allow two wild cards. The first is an underscore which matches any single one character. The second is a percent symbol which matches zero or more of any character.
- LIKE with "_" is therefore the same as the "." regular expression.
- LIKE with "%" is therefore the same as ".*" regular expression.
db:lt
- db:lt(field reference, value)
- Returns a database expression to test if the field in the sheet is less than the value.
db:lte
- db:lte(field reference, value)
- Returns a database expression to test if the field in the sheet is less than or equal to the value.
db:merge_unique
- db:merge_unique(sheet reference, table array)
- Merges the specified table array into the sheet, modifying any existing rows and adding any that don’t exist.
- This function is a convenience utility that allows you to quickly modify a sheet, changing existing rows and add new ones as appropriate. It ONLY works on sheets which have a unique index, and only when that unique index is only on a single field. For more complex situations you’ll have to do the logic yourself.
- The table array may contain tables that were either returned previously by db:fetch, or new tables that you’ve constructed with the correct fields, or any mix of both. Each table must have a value for the unique key that has been set on this sheet.
- For example, consider this database
local mydb = db:create("peopledb",
{
friends = {
name = "",
race = "",
level = 0,
city = "",
_index = { "city" },
_unique = { "name" }
}
);
- Here you have a database with one sheet, which contains your friends, their race, level, and what city they live in. Let’s say you want to fetch everyone who lives in San Francisco, you could do:
local results = db:fetch(mydb.friends, db:eq(mydb.friends.city, "San Francisco"))
- The tables in results are static, any changes to them are not saved back to the database. But after a major radioactive cataclysm rendered everyone in San Francisco a mutant, you could make changes to the tables as so:
for _, friend in ipairs(results) do
friend.race = "Mutant"
end
- If you are also now aware of a new arrival in San Francisco, you could add them to that existing table array:
results[#results+1] = {name="Bobette", race="Mutant", city="San Francisco"}
- And commit all of these changes back to the database at once with:
db:merge_unique(mydb.friends, results)
- The db:merge_unique function will change the city values for all the people who we previously fetched, but then add a new record as well.
db:not_between
- db:not_between(field reference, lower_bound, upper_bound)
- Returns a database expression to test if the field in the sheet is not a value between lower_bound and upper_bound. This only really makes sense for numbers and Timestamps.
db:not_eq
- db:not_eq(field reference, value)
- Returns a database expression to test if the field in the sheet is NOT equal to the value.
db:not_in
- db:not_in(field reference, table array)
- Returns a database expression to test if the field in the sheet is not one of the values in the table array.
- See also: db:in_
db:not_like
- db:not_like(field reference, pattern)
- Returns a database expression to test if the field in the sheet does not match the specified pattern.
- LIKE patterns are not case-sensitive, and allow two wild cards. The first is an underscore which matches any single one character. The second is a percent symbol which matches zero or more of any character.
- LIKE with "_" is therefore the same as the "." regular expression.
- LIKE with "%" is therefore the same as ".*" regular expression.
db:OR
- db:OR(sub-expression1, sub-expression2)
- Returns a compound database expression that combines both of the simple expressions passed into it; these expressions should be generated with other db: functions such as db:eq, db:like, db:lt and the like.
- This compound expression will find any item that matches either the first or the second sub-expression.
db:query_by_example
- db:query_by_example(sheet reference, example table)
- Returns a query for database content matching the given example, which can be used for db:delete, db:fetch and db:set. Different fields of the example are AND connected.
- Field values should be strings and can contain the following values:
- literal strings to search for
- comparison terms prepended with <, >, >=, <=, !=, <> for number and date comparisons
- ranges with :: between lower and upper bound
- different single values combined by || as OR
- strings containing % for a single and _ for multiple wildcard characters

- Example
mydb = db:create("mydb",
{
sheet = {
name = "", id = 0, city = "",
_index = { "name" },
_unique = { "id" },
_violations = "FAIL"
}
})
test_data = {
{name="Ixokai", city="Magnagora", id=1},
{name="Vadi", city="New Celest", id=2},
{name="Heiko", city="Hallifax", id=3},
{name="Keneanung", city="Hashan", id=4},
{name="Carmain", city="Mhaldor", id=5},
{name="Ixokai", city="Hallifax", id=6},
}
db:add(mydb.sheet, unpack(test_data))
res = db:fetch(mydb.sheet, db:query_by_example(mydb.sheet, { name = "Ixokai"}))
display(res)
--[[
Prints
{
{
id = 1,
name = "Ixokai",
city = "Magnagora"
},
{
id = 6,
name = "Ixokai",
city = "Hallifax"
}
}
--]]
mydb = db:create("mydb",
{
sheet = {
name = "", id = 0, city = "",
_index = { "name" },
_unique = { "id" },
_violations = "FAIL"
}
})
test_data = {
{name="Ixokai", city="Magnagora", id=1},
{name="Vadi", city="New Celest", id=2},
{name="Heiko", city="Hallifax", id=3},
{name="Keneanung", city="Hashan", id=4},
{name="Carmain", city="Mhaldor", id=5},
{name="Ixokai", city="Hallifax", id=6},
}
db:add(mydb.sheet, unpack(test_data))
res = db:fetch(mydb.sheet, db:query_by_example(mydb.sheet, { name = "Ixokai", id = "1"}))
display(res)
--[[
Prints
{
id = 1,
name = "Ixokai",
city = "Magnagora"
}
--]]
db:Timestamp
- db:Timestamp(time)
- Returns a table that will be converted to an appropriate time. If the time argument is a table, it will be converted to the current OS time; if it is a number, it will be intrepreted as a Unix epoch time; if it is nil, it will be converted to a SQL NULL; it can also have the value of "CURRENT_TIMESTAMP", which will be converted to the corresponding SQL keyword.
db:Null
- db:Null()
- Returns a table that will be interpreted as the NULL SQL keyword.
db:safe_name
- db:safe_name(string)
- Strips all non-alphanumeric characters from the input string.Mainly used to sanitize database names.
db:set
- db:set(field reference, value, query)
- The db:set function allows you to set a certain field to a certain value across an entire sheet. Meaning, you can change all of the last_read fields in the sheet to a certain value, or possibly only the last_read fields which are in a certain city. The query argument can be any value which is appropriate for db:fetch, even nil which will change the value for the specified column for EVERY row in the sheet.
- For example, consider a situation in which you are tracking how many times you find a certain type of egg during Easter. You start by setting up your database and adding an Eggs sheet, and then adding a record for each type of egg.
- Example
local mydb = db:create("egg database", {eggs = {color = "", last_found = db.Timestamp(false), found = 0}})
db:add(mydb.eggs,
{color = "Red"},
{color = "Blue"},
{color = "Green"},
{color = "Yellow"},
{color = "Black"}
)
- Now, you have three columns. One is a string, one a timestamp (that ends up as nil in the database), and one is a number.
- You can then set up a trigger to capture from the game the string, "You pick up a (.*) egg!", and you end up arranging to store the value of that expression in a variable called "myegg".
- To increment how many we found, we will do this:
myegg = "Red" -- We will pretend a trigger set this.
db:set(mydb.eggs.found, db:exp("found + 1"), db:eq(mydb.eggs.color, myegg))
db:set(mydb.eggs.last_found, db.Timestamp("CURRENT_TIMESTAMP"), db:eq(mydb.eggs.color, myegg))
- This will go out and set two fields in the Red egg sheet; the first is the found field, which will increment the value of that field (using the special db:exp function). The second will update the last_found field with the current time.
- Once this contest is over, you may wish to reset this data but keep the database around. To do that, you may use a more broad use of db:set as such:
db:set(mydb.eggs.found, 0)
db:set(mydb.eggs.last_found, nil)
db:update
- db:update(sheet reference, table)
- This function updates a row in the specified sheet, but only accepts a row which has been previously obtained by db:fetch. Its primary purpose is that if you do a db:fetch, then change the value of a field or tow, you can save back that table.
- Example
local mydb = db:get_database("my database")
local bob = db:fetch(mydb.friends, db:eq(mydb.friends.name, "Bob"))[1]
bob.notes = "He's a really awesome guy."
db:update(mydb.friends, bob)
- This obtains a database reference, and queries the friends sheet for someone named Bob. As this returns a table array containing only one item, it assigns that one item to the local variable named bob. We then change the notes on Bob, and pass it into db:update() to save the changes back.
db:_sql_convert
- db:_sql_convert(value)
- Converts a data value in Lua to its SQL equivalent; notably it will also escape single-quotes to prevent inadvertent SQL injection. In addition, it will convert Lua tables with a _timestamp key to the appropriate time (possibly CURRENT_TIMESTAMP) and Lua tables with a _isNull key to the NULL SQL keyword.
db:_sql_values
- db:_sql_values(values)
- This quotes values to be passed into an INSERT or UPDATE operation in a SQL list. Meaning, it turns {x="this", y="that", z=1} into ('this', 'that', 1). It is intelligent with data-types; strings are automatically quoted (with internal single quotes escaped), nil turned into NULL, timestamps converted to integers, and such.
Transaction Functions
These functions facilitate use of transactions with a database. This can safely be ignored in most cases, but can provide useful functionality in specific circumstances. Transactions allow batching sets of changes to be accepted or rejected at a later point. Bear in mind that transactions affect an entire database.
db:_begin
- db:_begin()
- This function halts all automatic disk writes for the database. This can be especially helpful when running large or frequent (multiple times a second) database edits through multiple function calls to prevent Mudlet freezing or jittering. Calling this on a database already in a transaction will have no effect, but will not produce an error.
local mydb = db:get_database("my_database")
mydb:_begin()
-- do other things as needed
db:_commit
- db:_commit()
- This function forces the database to save all changes to disk, beginning a new transaction in the process.
local mydb = db:get_database("my_database")
mydb:_begin()
-- do other things as needed
mydb:_commit()
db:_end
- db:_end()
- This function re-enables automatic disk writes for the database. It will not commit changes to disk on its own, nor will it end the current transaction. Using db:_commit() or any database function that writes changes after this will save the transaction to disk. Using db:_begin again before this happens will continue the previous transaction without writing anything to disk.
local mydb = db:get_database("my_database")
mydb:_end()
db:_rollback
- db:_rollback()
- This function will discard all changes that have occurred during the current transaction and begin a new one. Use of this function will not toggle the auto-write state of the database.
local mydb = db:get_database("my_database")
mydb:_begin()
-- do other things as needed
mydb:_rollback()
Date & Time Functions
A collection of functions for handling date & time.
datetime:parse
- datetime:parse(source, format, as_epoch)
- Parses the specified source string, according to the format if given, to return a representation of the date/time. If as_epoch is provided and true, the return value will be a Unix epoch — the number of seconds since 1970. This is a useful format for exchanging date/times with other systems. If as_epoch is false, then a Lua time table will be returned. Details of the time tables are provided in the Lua Manual.
- Supported Format Codes
%b = Abbreviated Month Name
%B = Full Month Name
%d = Day of Month
%H = Hour (24-hour format)
%I = Hour (12-hour format, requires %p as well)
%p = AM or PM
%m = 2-digit month (01-12)
%M = 2-digit minutes (00-59)
%S = 2-digit seconds (00-59)
%y = 2-digit year (00-99), will automatically prepend 20 so 10 becomes 2010 and not 1910.
%Y = 4-digit year.
getEpoch
- seconds = getEpoch()
- This function returns the seconds since Unix epoch with milliseconds.
- Example
getEpoch() -- will show e.g. 1523555867.191
getTime
- time = getTime([return as string, [custom time format]])
- "return string" is a boolean value (in Lua anything but false or nil will translate to true). If false, the function will return a table in the following format:
{ 'min': #, 'year': #, 'month': #, 'day': #, 'sec': #, 'hour': #, 'msec': # }
If true, it will return the date and time as a string using a format passed to the "custom time format" arg or if none is supplied the default of "yyyy.MM.dd hh:mm:ss.zzz":
2012.02.18 00:52:52.489
Format expressions:
h the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display) hh the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display) H the hour without a leading zero (0 to 23, even with AM/PM display) HH the hour with a leading zero (00 to 23, even with AM/PM display) m the minute without a leading zero (0 to 59) mm the minute with a leading zero (00 to 59) s the second without a leading zero (0 to 59) ss the second with a leading zero (00 to 59) z the milliseconds without leading zeroes (0 to 999) zzz the milliseconds with leading zeroes (000 to 999) AP or A use AM/PM display. AP will be replaced by either "AM" or "PM". ap or a use am/pm display. ap will be replaced by either "am" or "pm". d the day as number without a leading zero (1 to 31) dd the day as number with a leading zero (01 to 31) ddd the abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses QDate::shortDayName(). dddd the long localized day name (e.g. 'Monday' to 'Qt::Sunday'). Uses QDate::longDayName(). M the month as number without a leading zero (1-12) MM the month as number with a leading zero (01-12) MMM the abbreviated localized month name (e.g. 'Jan' to 'Dec'). Uses QDate::shortMonthName(). MMMM the long localized month name (e.g. 'January' to 'December'). Uses QDate::longMonthName(). yy the year as two digit number (00-99) yyyy the year as four digit number
All other input characters will be ignored. Any sequence of characters that are enclosed in single quotes will be treated as text and not be used as an expression. Two consecutive single quotes ('') are replaced by a single single quote in the output.
- Example
-- Get time as a table
getTime()
-- Get time with default string
getTime(true)
-- Get time without date and milliseconds
getTime(true, "hh:mm:ss")
getTimestamp
- time = getTimestamp([console_name], lineNumber)
- Returns the timestamp string as it’s seen when you enable the timestamps view (blue i button bottom right).
- Example
-- echo the timestamp of the current line in a trigger:
echo(getTimestamp(getLineCount()))
-- insert the timestamp into a "chat" miniconsole
cecho("chat", "<red>"..getTimestamp(getLineCount()))
shms
- shms(seconds, bool)
- Converts seconds into hours, minutes and seconds, displaying the result as a table. An optional second argument can be passed to return the result as an echo.

- Example
--Determine the total number of seconds and display:
shms(65535, true)
File System Functions
A collection of functions for interacting with the file system.
io.exists
- io.exists(path)
- Checks to see if a given file or folder exists.
- If it exists, it’ll return the Lua true boolean value, otherwise false.
- See lfs.attributes() for a cross-platform solution.
- Example
-- This example works on Linux only
if io.exists("/home/vadi/Desktop") then
echo("This folder exists!")
else
echo("This folder doesn't exist.")
end
-- This example will work on both Windows and Linux.
if io.exists("/home/vadi/Desktop/file.tx") then
echo("This file exists!")
else
echo("This file doesn't exist.")
end
lfs.attributes
- infoTable = lfs.attributes(path)
- Returns a table with detailed information regarding a file or directory, or nil if path is invalid / file or folder does not exist.
- Example
fileInfo = lfs.attributes("/path/to/file_or_directory")
if fileInfo then
if fileInfo.mode == "directory" then
echo("Path points to a directory.")
elseif fileInfo.mode == "file" then
echo("Path points to a file.")
else
echo("Path points to: "..fileInfo.mode)
end
display(fileInfo) -- to see the detailed information
else
echo("The path is invalid (file/directory doesn't exist)")
end
Mapper Functions
These are functions that are to be used with the Mudlet Mapper. The mapper is designed to be generic - it only provides the display and pathway calculations, to be used in Lua scripts that are tailored to the game you're playing. For a collection of pre-made scripts and general mapper talk, visit the mapper section of the forums.
To register a script as a mapping one with Mudlet (so Mudlet knows the profile has one and won't bother the user when they open the map), please do this in your script:
mudlet = mudlet or {}; mudlet.mapper_script = true
addAreaName
- areaID = addAreaName(areaName)
- Adds a new area name and returns the new (positive) area ID for the new name. If the name already exists, older versions of Mudlet returned -1 though since 3.0 the code will return nil and an error message.
- See also: deleteArea(), addRoom()
- Example
local newId, err = addAreaName(string.random(10))
if newId == nil or newId < 1 or err then
echo("That area name could not be added - error is: ".. err.."\n")
else
cecho("<green>Created new area with the ID of "..newId..".\n")
end
addCustomLine
- addCustomLine(roomID, id_to, direction, style, color, arrow)
- See also: getCustomLines(), removeCustomLine()
- Adds a new/replaces an existing custom exit line to the 2D mapper for the room with the Id given.
- Parameters
- roomID:
- Room ID to attach the custom line to.
- id_to:
- EITHER: a room Id number, of a room on same area who's x and y coordinates are used as the other end of a SINGLE segment custom line (it does NOT imply that is what the exit it represent goes to, just the location of the end of the line);
- OR: a table of sets of THREE (x,y and z) coordinates in that order, x and y can be decimals, z is an integer (and must be present and be the same for all points on the line, though it is irrelevant to what is produced as the line is drawn on the same z-coordinate as the room that the line is attached to!)
- direction: a string to associate the line with a valid exit direction, "n", "ne", "e", "se", "s", "sw", "w", "nw", "up", "down", "in" or "out" or a special exit (before Mudlet 3.17 this was case-sensitive and cardinal directions had to be uppercase).
- style: a string, one of: "solid line", "dot line", "dash line", "dash dot line" or "dash dot dot line" exactly.
- color: a table of three integers between 0 and 255 as the custom line color as the red, green and blue components in that order.
- arrow: a boolean which if true will set the custom line to have an arrow on the end of the last segment.

- Examples
-- create a line from roomid 1 to roomid 2
addCustomLine(1, 2, "N", "dot line", {0, 255, 255}, true)
addCustomLine(1, {{4.5, 5.5, 3}, {4.5, 9.5, 3}, {6.0, 9.5, 3}}, "climb Rope", "dash dot dot line", {128, 128, 0}, false)
A bigger example that'll create a new area and the room in it:
local areaid = addAreaName("my first area")
local newroomid = createRoomID()
addRoom(newroomid)
setRoomArea(newroomid, "my first area")
setRoomCoordinates(newroomid, 0, 0, 0)
local otherroomid = createRoomID()
addRoom(otherroomid)
setRoomArea(otherroomid, "my first area")
setRoomCoordinates(otherroomid, 0, 5, 0)
addSpecialExit(newroomid, otherroomid, "climb Rope")
addCustomLine(newroomid, {{4.5, 5.5, 3}, {4.5, 9.5, 3}, {6.0, 9.5, 3}}, "climb Rope", "dash dot dot line", {128, 128, 0}, false)
centerview(newroomid)
addMapEvent
- addMapEvent(uniquename, event name, parent, display name, arguments)
- Adds a new entry to an existing mapper right-click entry. You can add one with addMapMenu. If there is no display name, it will default to the unique name (which otherwise isn't shown and is just used to differentiate this entry from others). event name is the Mudlet event that will be called when this is clicked on, and arguments will be passed to the handler function.
- See also: addMapMenu(), removeMapEvent(), getMapEvents()
- Example
addMapEvent("room a", "onFavorite") -- will make a label "room a" on the map menu's right click that calls onFavorite
addMapEvent("room b", "onFavorite", "Favorites", "Special Room!", 12345, "arg1", "arg2", "argn")
The last line will make a label "Special Room!" under the "Favorites" menu that upon clicking will raise an event with all the arguments.
addMapMenu("Room type")
addMapEvent("markRoomsAsDeathTrap", "onMapMarkSelectedRooms", "Room type", "Mark selected rooms as Death Trap")
addMapEvent("markRoomsAsOneRoom", "onMapMarkSelectedRooms", "Room type", "Mark selected rooms as single-pass")
function onMapMarkSelectedRooms(event, markRoomType)
local selectedRooms = getMapSelection()["rooms"]
for i, val in ipairs(selectedRooms) do
if markRoomType == "markRoomsAsDeathTrap" then
local r, g, b = unpack(color_table.black)
--death trap
setRoomEnv(val, 300)
--death traps Env
setCustomEnvColor(300, r, g, b, 255)
setRoomChar(val, "☠️")
lockRoom(val, true)
elseif markRoomType == "markRoomsAsOneRoom" then
local r, g, b = unpack(color_table.LightCoral)
--single-pass
setRoomEnv(val, 301)
--one room Env
setCustomEnvColor(301, r, g, b, 255)
setRoomChar(val, "🚹")
end
end
updateMap()
end
registerAnonymousEventHandler("onMapMarkSelectedRooms", "onMapMarkSelectedRooms")
This create menu and two submenu options: "Mark selected rooms as Death Trap" and "Mark selected rooms as single-pass"
addMapMenu
- addMapMenu(uniquename, parent, display name)
- Adds a new submenu to the right-click menu that opens when you right-click on the mapper. You can then add more submenus to it, or add entries with addMapEvent().
- See also: addMapEvent(), removeMapEvent(), getMapEvents()
- Example
-- This will create a menu named: Favorites.
addMapMenu("Favorites")
-- This will create a submenu with the unique id 'Favorites123' under 'Favorites' with the display name of 'More Favorites'.
addMapMenu("Favorites1234343", "Favorites", "More Favorites")
addRoom
- addRoom(roomID)
- Creates a new room with the given ID, returns true if the room was successfully created.
Note: If you're not using incremental room IDs but room IDs stitched together from other factors or in-game hashes for room IDs - and your room IDs are starting off at 250+million numbers, you need to look into incrementally creating Mudlets room IDs with createRoomID() and associating your room IDs with Mudlets via setRoomIDbyHash() and getRoomIDbyHash(). The reason being is that Mudlet's A* pathfinding implementation from boost cannot deal with extremely large room IDs because the resulting matrices it creates for pathfinding are enormously huge.
Note: Creating your own mapping script? Check out more information here.
- See also: createRoomID()
- Example
local newroomid = createRoomID()
addRoom(newroomid)
addSpecialExit
- addSpecialExit(roomIDFrom, roomIDTo, moveCommand)
- Creates a one-way from one room to another, that will use the given command for going through them.
- See also: clearSpecialExits(), removeSpecialExit(), setExit()
- Example
-- add a one-way special exit going from room 1 to room 2 using the 'pull rope' command
addSpecialExit(1, 2, "pull rope")
Example in an alias:
-- sample alias pattern: ^spe (\d+) (.*?)$
-- currentroom is your current room ID in this example
addSpecialExit(currentroom,tonumber(matches[2]), matches[3])
echo("\n SPECIAL EXIT ADDED TO ROOMID:"..matches[2]..", Command:"..matches[3])
centerview(currentroom)
auditAreas
- auditAreas()
- Initiates a consistency check on the whole map: All rooms, areas, and their composition. This is also done automatically whenever you first open your map, so probably seldom necessary to do manually. Will output findings to screen and/or logfile for later review.
- See also: saveMap(), removeMapEvent(), getMapEvents()
centerview
- centerview (roomID)
- Centers the map view onto the given room ID. The map must be open to see this take effect. This function can also be used to see the map of an area if you know the number of a room there and the area and room are mapped.
- See also: getPlayerRoom(), updateMap()
clearAreaUserData
- clearAreaUserData(areaID)
- Parameter
- areaID - ID number for area to clear.
- Clears all user data from a given area. Note that this will not touch the room user data.
- See also: setAreaUserData(), getAllAreaUserData(), clearAreaUserDataItem(), clearRoomUserData()
- Example
display(clearAreaUserData(34))
-- I did have data in that area, so it returns:
true
display(clearAreaUserData(34))
-- There is no data NOW, so it returns:
false

clearAreaUserDataItem
- clearAreaUserDataItem(areaID, key)
- Removes the specific key and value from the user data from a given area.
- See also: setAreaUserData(), clearAreaUserData(), clearRoomUserDataItem()

- Example
display(getAllAreaUserData(34))
{
description = [[<area description here>]],
ruler = "Queen Morgase Trakand"
}
display(clearAreaUserDataItem(34,"ruler"))
true
display(getAllAreaUserData(34))
{
description = [[<area description here>]],
}
display(clearAreaUserDataItem(34,"ruler"))
false
clearMapSelection
- clearMapSelection()
- Clears any selected rooms from the map (i.e. they are highlighted in orange).
- Returns true if rooms are successfully cleared, false if nothing selected or cleared.
- See also getMapSelection()
clearMapUserData
- clearMapUserData()
- Clears all user data stored for the map itself. Note that this will not touch the area or room user data.
- See also: setMapUserData(), clearRoomUserData(), clearAreaUserData()

- Example
display(clearMapUserData())
-- I did have user data stored for the map, so it returns:
true
display(clearMapUserData())
-- There is no data NOW, so it returns:
false
clearMapUserDataItem
- clearMapUserDataItem(mapID, key)
- Removes the specific key and value from the user data from the map user data.
- See also: setMapUserData(), clearMapUserData(), clearAreaRoomUserData()
- Example
display(getAllMapUserData())
{
description = [[<map description here>]],
last_modified = "1483228799"
}
display(clearMapUserDataItem("last_modified"))
true
display(getAllMapUserData())
{
description = [[<map description here>]],
}
display(clearMapUserDataItem("last_modified"))
false

clearRoomUserData
- clearRoomUserData(roomID)
- Clears all user data from a given room.
- See also: setRoomUserData(), clearRoomUserDataItem()
Note: Returns a boolean true if any data was removed from the specified room and false if there was nothing to erase since Mudlet 3.0.
- Example
display(clearRoomUserData(3441))
-- I did have data in that room, so it returns:
true
display(clearRoomUserData(3441))
-- There is no data NOW, so it returns:
false
clearRoomUserDataItem
- clearRoomUserDataItem(roomID, key)
- Removes the specific key and value from the user data from a given room.
- Returns a boolean true if data was found against the give key in the user data for the given room and it is removed, will return false if exact key not present in the data. Returns nil if the room for the roomID not found.
- See also: setRoomUserData(), clearRoomUserData(), clearAreaUserDataItem()
- Example
display(getAllRoomUserData(3441))
{
description = [[
From this ledge you can see out across a large cavern to the southwest. The
east side of the cavern is full of stalactites and stalagmites and other
weird rock formations. The west side has a path through it and an exit to the
south. The sound of falling water pervades the cavern seeming to come from
every side. There is a small tunnel to your east and a stalactite within arms
reach to the south. It appears to have grown till it connects with the
stalagmite below it. Something smells... Yuck you are standing in bat guano!]],
doorname_up = "trapdoor"
}
display(clearRoomUserDataItem(3441,"doorname_up"))
true
display(getAllRoomUserData(3441))
{
description = [[
From this ledge you can see out across a large cavern to the southwest. The
east side of the cavern is full of stalactites and stalagmites and other
weird rock formations. The west side has a path through it and an exit to the
south. The sound of falling water pervades the cavern seeming to come from
every side. There is a small tunnel to your east and a stalactite within arms
reach to the south. It appears to have grown till it connects with the
stalagmite below it. Something smells... Yuck you are standing in bat guano!]],
}
display(clearRoomUserDataItem(3441,"doorname_up"))
false

clearSpecialExits
- clearSpecialExits(roomID)
- Removes all special exits from a room.
- See also: addSpecialExit(), removeSpecialExit()
- Example
clearSpecialExits(1337)
if #getSpecialExits(1337) == 0 then -- clearSpecialExits will never fail on a valid room ID, this is an example
echo("All special exits successfully cleared from 1337.\n")
end
closeMapWidget
- closeMapWidget()
- closes (hides) the map window (similar to clicking on the map icon)

- See also: openMapWidget(), moveMapWidget(), resizeMapWidget()
connectExitStub
- connectExitStub(fromID, direction) or connectExitStub(fromID, toID, [direction])
- Connects existing rooms with matching exit stubs. If you only give it a roomID and a direction, it'll work out which room should be linked to it that has an appropriate opposite exit stub and is located in the right direction. You can also just specify from and to room IDs, and it'll smartly use the right direction to link in. Lastly, you can specify all three arguments - fromID, toID and the direction (in that order) if you'd like to be explicit, or use setExit() for the same effect.
- Parameters
- fromID:
- Room ID to set the exit stub in.
- direction:
- You can either specify the direction to link the room in, and/or a specific room ID (see below). Direction can be specified as a number, short direction name ("nw") or long direction name ("northwest").
- toID:
- The room ID to link this room to. If you don't specify it, the mapper will work out which room should be logically linked.
- See also: setExitStub(), getExitStubs()
- Example
-- try and connect all stubs that are in a room
local stubs = getExitStubs(roomID)
if stubs then
for i,v in pairs(stubs) do
connectExitStub(roomID, v)
end
end
createMapLabel
- labelID = createMapLabel(areaID, text, posX, posY, posZ, fgRed, fgGreen, fgBlue, bgRed, bgGreen, bgBlue[, zoom, fontSize, showOnTop, noScaling, fontName, foregroundTransparency, backgroundTransparency, temporary])
- Creates a text label on the map at given coordinates, with the given background and foreground colors. It can go above or below the rooms, scale with zoom or stay a static size. From Mudlet 4.17.0 an additional parameter (assumed to be false if not given from then) makes the label NOT be saved in the map file which, if the image can be regenerated on future loading from a script can reduce the size of the saved map somewhat. It returns a label ID that you can use later for deleting it.
- The coordinates 0,0 are in the middle of the map, and are in sync with the room coordinates - so using the x,y values of getRoomCoordinates() will place the label near that room.
- See also: getMapLabel(), getMapLabels(), deleteMapLabel, createMapImageLabel()
Note: Some changes were done prior to 4.13 (which exactly? function existed before!) - see corresponding PR and update here!
- Parameters
- areaID:
- Area ID where to put the label.
- text:
- The text to put into the label. To get a multiline text label add a '\n' between the lines.
- posX, posY, posZ:
- Position of the label in (floating point numbers) room coordinates.
- fgRed, fgGreen, fgBlue:
- Foreground color or text color of the label.
- bgRed, bgGreen, bgBlue:
- Background color of the label.
- zoom:
- (optional) Zoom factor of the label if noScaling is false. Higher zoom will give higher resolution of the text and smaller size of the label. Default is 30.0.
- fontSize:
- (optional, but needed if zoom is provided) Size of the font of the text. Default is 50.
- showOnTop:
- (optional) If true the label will be drawn on top of the rooms and if it is false the label will be drawn as a background, defaults to true if not given.
- noScaling:
- (optional) If true the label will have the same size when you zoom in and out in the mapper, If it is false the label will scale when you zoom the mapper, defaults to true if not given.
- fontName:
- (optional) font name to use.
- foregroundTransparency
- (optional) transparency of the text on the label, defaults to 255 (in range of 0 to 255) or fully opaque if not given.
- backgroundTransparency
- (optional) transparency of the label background itself, defaults to 50 (in range of 0 to 255) or significantly transparent if not given.
- temporary
- (optional, from Mudlet version 4.17.0) if true does not save the image that the label makes in map save files, defaults to false if not given, or for prior versions of Mudlet.
- Example
-- the first 50 is some area id, the next three 0,0,0 are coordinates - middle of the area
-- 255,0,0 would be the foreground in RGB, 23,0,0 would be the background RGB
-- zoom is only relevant when when you're using a label of a static size, so we use 0
-- and we use a font size of 20 for our label, which is a small medium compared to the map
local labelid = createMapLabel( 50, "my map label", 0,0,0, 255,0,0, 23,0,0, 0,20)
-- to create a multi line text label we add '\n' between lines
-- the position is placed somewhat to the northeast of the center of the map
-- this label will be scaled as you zoom the map.
local labelid = createMapLabel( 50, "1. Row One\n2. Row 2", .5,5.5,0, 255,0,0, 23,0,0, 30,50, true, false)
local x,y,z = getRoomCoordinates(getPlayerRoom())
createMapLabel(getRoomArea(getPlayerRoom()), "my map label", x,y,z, 255,0,0, 23,0,0, 0,20, false, true, "Ubuntu", 255, 100)
createMapImageLabel
- labelID = createMapImageLabel(areaID, filePath, posx, posy, posz, width, height, zoom, showOnTop[, temporary])
- Creates an image label on the map at the given coordinates, with the given dimensions and zoom. You might find the default room and image size correlation to be too big - try reducing the width and height of the image then, while also zooming in the same amount. From Mudlet 4.17.0 an additional parameter (assumed to be false if not given from then) makes the label NOT be saved in the map file which, if the image can be regenerated on future loading from a external file available when the map file is loaded, can avoid expanding the size of the saved map considerably.
- The coordinates 0,0 are in the middle of the map, and are in sync with the room coordinates - so using the x,y values of getRoomCoordinates() will place the label near that room.
- See also: createMapLabel, deleteMapLabel
- Example
-- 138 is our pretend area ID
-- next, inside [[]]'s, is the exact location of our image
-- 0,0,0 are the x,y,z coordinates - so this will place it in the middle of the map
-- 482 is the width of the image - we divide it by 100 to scale it down, and then we'll zoom it by 100 - making the image take up about 4 rooms in width then
-- 555 is the original height of the image
-- 100 is how much we zoom it by, 1 would be no zoom
-- false to make it go below our rooms
-- (from 4.17.0) true to not save the label's image in the map file afterwards
createMapImageLabel(138, [[/home/vadi/Pictures/You only see what shown.png]], 0,0,0, 482/100, 555/100, 100, false, true)
createMapper
- createMapper([name of userwindow], x, y, width, height)
- Creates a miniconsole window for the mapper to render in, the with the given dimensions. You can only create one mapper at a time, and it is not currently possible to have a label on or under the mapper - otherwise, clicks won't register.
Note: name of userwindow available in Mudlet 4.6.1+
Note: If this command is not used then clicking on the Main Toolbar's Map button will create a dock-able widget (that can be floated free to anywhere on the Desktop, it can be resized and does not have to even reside on the same monitor should there be multiple screens in your system). Further clicks on the Map button will toggle between showing and hiding the map whether it was created using the createMapper function or as a dock-able widget.
- Example
createMapper(0,0,300,300) -- creates a 300x300 mapper in the top-left corner of Mudlet
setBorderLeft(305) -- adds a border so text doesn't underlap the mapper display
-- another example:
local main = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="mapper container"})
local mapper = Geyser.Mapper:new({
name = "mapper",
x = "70%", y = 0, -- edit here if you want to move it
width = "30%", height = "50%"
}, main)
createRoomID
- usableId = createRoomID([minimumStartingRoomId])
- Returns the lowest possible room ID you can use for creating a new room. If there are gaps in room IDs your map uses it, this function will go through the gaps first before creating higher IDs.
- Parameters
- minimumStartingRoomId (optional, available in Mudlet 3.0+):
- If provided, specifies a roomID to start searching for an empty one at, instead of 1. Useful if you'd like to ensure certain areas have specific room number ranges, for example. If you you're working with a huge map, provide the last used room ID to this function for an available roomID to be found a lot quicker.
- See also: addRoom()
deleteArea
- deleteArea(areaID or areaName)
- Deletes the given area and all rooms in it. Returns true on success or nil + error message otherwise.
- See also: addAreaName()
- Parameters
- areaID:
- Area ID to delete, or:
- areaName (available in Mudlet 3.0+):
- Area name to delete.
- Example
-- delete by areaID
deleteArea(23)
-- or since Mudlet 3.0, by area name
deleteArea("Big city")
deleteMap
- deleteMap()
Deletes the entire map. This may be useful whilst initially setting up a mapper package for a new Game to clear faulty map data generated up to this point.
- See also: loadMap()

- Returns
- true on success or nil and an error message on failure, if successful it will also refresh the map display to show the result - which will be the "blank" screen with a warning message of the form "No rooms in the map - load another one, or start mapping from scratch to begin."
Note: Prior to the introduction of this function, the recommended method to achieve the same result was to use loadMap() with a non-existent file-name, such as "_" however that would also cause an "[ ERROR ]" type message to appear on the profile's main console.
- Example
deleteMap()
deleteMapLabel
- deleteMapLabel(areaID, labelID)
- Deletes a map label from a specific area.
- See also: createMapLabel()
- Example
deleteMapLabel(50, 1)
deleteRoom
- deleteRoom(roomID)
- Deletes an individual room, and unlinks all exits leading to and from it.
- Example
deleteRoom(335)
disableMapInfo
- disableMapInfo(label)
Disable the particular map info - same as toggling off checkbox from select box under mapper.
- Parameters
- label:
- Name under which map info to be disabled was registered.
- See also: registerMapInfo(), enableMapInfo(), killMapInfo()

enableMapInfo
- enableMapInfo(label)
Enable the particular map info - same as toggling on checkbox from select box under mapper.
- Parameters
- label:
- Name under which map info to be enabled was registered.
- See also: registerMapInfo(), disableMapInfo(), killMapInfo()

getAllAreaUserData
- dataTable = getAllAreaUserData(areaID)
- Returns all the user data items stored in the given area ID; will return an empty table if there is no data stored or nil if there is no such area with that ID.
- Example
display(getAllAreaUserData(34))
--might result in:--
{
country = "Andor",
ruler = "Queen Morgase Trakand"
}

getAllMapUserData
- dataTable = getAllMapUserData()
- Returns all the user data items stored at the map level; will return an empty table if there is no data stored.
- See also: getMapUserData()
- Example
display(getAllMapUserData())
--might result in:--
{
description = [[This map is about so and so game]],
author = "Bob",
["last updated"] = "December 5, 2020"
}

getAllRoomEntrances
- exitsTable = getAllRoomEntrances(roomID)
- Returns an indexed list of normal and special exits leading into this room. In case of two-way exits, this'll report exactly the same rooms as getRoomExits(), but this function has the ability to pick up one-way exits coming into the room as well.

- Example
-- print the list of rooms that have exits leading into room 512
for _, roomid in ipairs(getAllRoomEntrances(512)) do
print(roomid)
end
- See also: getRoomExits()
getAllRoomUserData
- dataTable = getAllRoomUserData(roomID)
- Returns all the user data items stored in the given room ID; will return an empty table if there is no data stored or nil if there is no such room with that ID. Can be useful if the user was not the one who put the data in the map in the first place!
- See also
- getRoomUserDataKeys() - for a related command that only returns the data keys.

- Example
display(getAllRoomUserData(3441))
--might result in:--
{
description = [[
From this ledge you can see out across a large cavern to the southwest. The
east side of the cavern is full of stalactites and stalagmites and other
weird rock formations. The west side has a path through it and an exit to the
south. The sound of falling water pervades the cavern seeming to come from
every side. There is a small tunnel to your east and a stalactite within arms
reach to the south. It appears to have grown till it connects with the
stalagmite below it. Something smells... Yuck you are standing in bat guano!]],
doorname_up = "trapdoor"
}
getAreaExits
- roomTable = getAreaExits(areaID, showExits)
- Returns a table (indexed or key-value) of the rooms in the given area that have exits leading out to other areas - that is, border rooms.
- See also
- setExit(), getRoomExits()
- Parameters
- areaID:
- Area ID to list the exits for.
- showExits:
- Boolean argument, if true then the exits that lead out to another area will be listed for each room.
- Example
-- list all border rooms for area 44:
getAreaExits(44)
-- returns:
--[[
{
7091,
10659,
11112,
11122,
11133,
11400,
12483,
24012
}
]]
-- list all border rooms for area 44, and the exits within them that go out to other areas:
getAreaExits(44, true)
--[[
{
[12483] = {
north = 27278
},
[11122] = {
["enter grate"] = 14551
},
[11112] = {
["enter grate"] = 14829
},
[24012] = {
north = 22413
},
[11400] = {
south = 10577
},
[11133] = {
["enter grate"] = 15610
},
[7091] = {
down = 4411
},
[10659] = {
["enter grate"] = 15510
}
}
]]
getAreaRooms
- getAreaRooms(area id)
- Returns an indexed table with all rooms IDs for a given area ID (room IDs are values), or nil if no such area exists.
- Example
-- using the sample findAreaID() function defined in the getAreaTable() example,
-- we'll define a function that echo's us a nice list of all rooms in an area with their ID
function echoRoomList(areaname)
local id, msg = findAreaID(areaname)
if id then
local roomlist, endresult = getAreaRooms(id), {}
-- obtain a room list for each of the room IDs we got
for _, id in pairs(roomlist) do
endresult[id] = getRoomName(id)
end
-- now display something half-decent looking
cecho(string.format(
"List of all rooms in %s (%d):\n", msg, table.size(endresult)))
for roomid, roomname in pairs(endresult) do
cecho(string.format(
"%6s: %s\n", roomid, roomname))
end
elseif not id and msg then
echo("ID not found; " .. msg)
else
echo("No areas matched the query.")
end
end
getAreaTable
- areaTable = getAreaTable()
- Returns a key(area name)-value(area id) table with all known areas and their IDs.
Note: Some older versions of Mudlet return an area with an empty name and an ID of 0 included in it, you should ignore that.
- See also
- getAreaTableSwap()
- Example
-- example function that returns the area ID for a given area
function findAreaID(areaname)
local list = getAreaTable()
-- iterate over the list of areas, matching them with substring match.
-- if we get match a single area, then return it's ID, otherwise return
-- 'false' and a message that there are than one are matches
local returnid, fullareaname
for area, id in pairs(list) do
if area:find(areaname, 1, true) then
if returnid then return false, "more than one area matches" end
returnid = id; fullareaname = area
end
end
return returnid, fullareaname
end
-- sample use:
local id, msg = findAreaID("blahblah")
if id then
echo("Found a matching ID: " .. id)
elseif not id and msg then
echo("ID not found: " .. msg)
else
echo("No areas matched the query.")
end
getAreaTableSwap
- areaTable = getAreaTableSwap()
- Returns a key(area id)-value(area name) table with all known areas and their IDs. Unlike getAreaTable which won't show you all areas with the same name by different IDs, this function will.
Note: Some older versions of Mudlet return an area with an empty name and an ID of 0 included in it, you should ignore that.
getAreaUserData
- dataValue = getAreaUserData(areaID, key)
- Returns a specific data item stored against the given key for the given area ID number. This is very like the corresponding Room User Data command but intended for per area rather than for per room data (for storage of data relating to the whole map see the corresponding Map User Data commands.)
- Returns the user data value (string) stored at a given room with a given key (string), or a Lua nil and an error message if the key is not present in the Area User Data for the given Area ID. Use setAreaUserData() function for storing the user data.
- See also
- clearAreaUserData(), clearAreaUserDataItem(), getAllAreaUserData(), searchAreaUserData(), setAreaUserData()
- Example
display(getAreaUserData(34, "country"))
-- might produce --
"Andor"
getCustomEnvColorTable
- envcolors = getCustomEnvColorTable()
- Returns a table with customized environments, where the key is the environment ID and the value is a indexed table of rgb values.
- See also: setCustomEnvColor()
- Example
{
envid1 = {r, g, b, alpha},
envid2 = {r, g, b, alpha}
}
getCustomLines
- lineTable = getCustomLines(roomID)
- See also: addCustomLine(), removeCustomLine()
- Returns a table including all the details of the custom exit lines, if any, for the room with the id given.
- Parameters
- roomID:
- Room ID to return the custom line details of.

- Example
display getCustomLines(1)
{
["climb Rope"] = {
attributes = {
color = {
b = 0,
g = 128,
r = 128
},
style = "dash dot dot line",
arrow = false
},
points = {
{
y = 9.5,
x = 4.5
},
{
y = 9.5,
x = 6
},
[0] = {
y = 5.5,
x = 4.5
}
}
},
N = {
attributes = {
color = {
b = 255,
g = 255,
r = 0
},
style = "dot line",
arrow = true
},
points = {
[0] = {
y = 27,
x = -3
}
}
}
}
getCustomLines1
- lineTable = getCustomLines1(roomID)
This is a replacement for getCustomLines(...) that outputs the tables for the coordinates for the points on the custom line in an order and format that can be fed straight back into an addCustomLine(...) call; similarly the color parameters are also reported in the correct format to also be reused in the same manner. This function is intended to make it simpler for scripts to manipulate such lines.
- See also: addCustomLine(), removeCustomLine(), getCustomLines()

- Parameters
- roomID:
- Room ID to return the custom line details of.
- Returns
- a table including all the details of the custom exit lines, if any, for the room with the id given.
- Example
display getCustomLines1(1)
{
["climb Rope"] = {
attributes = {
color = { 128, 128, 0 },
style = "dash dot dot line",
arrow = false
},
points = { { 4.5, 5.5, 3 }, { 4.5, 9.5, 3 }, { 6, 9.5, 3 } }
},
N = {
attributes = {
color = { 0, 255, 255 },
style = "dot line",
arrow = true
},
points = { { -3, 27, 3 } }
}
}
getDoors
- doors = getDoors(roomID)
- Returns a key-value table with the cardinal direction as the key and the door value as a number. If there are no doors in a room, it returns an empty table.
- Parameters
- roomID:
- Room ID to check for doors in.
- See also: setDoor()
- Example
-- an example that displays possible doors in room 2334
local doors = getDoors(2334)
if not next(doors) then cecho("\nThere aren't any doors in room 2334.") return end
local door_status = {"open", "closed", "locked"}
for direction, door in pairs(doors) do
cecho("\nThere's a door leading in "..direction.." that is "..door_status[door]..".")
end
getExitStubs
- stubs = getExitStubs(roomid)
- Returns an indexed table (starting at 0) of the direction #'s that have an exit stub marked in them. You can use this information to connect earlier-made exit stubs between rooms when mapping.
- See also: setExitStub(), connectExitStub(), getExitStubs1()
- Example
-- show the exit stubs in room 6 as numbers
local stubs = getExitStubs(6)
for i = 0, #stubs do print(stubs[i]) end
Note: Previously would throw a lua error on non-existent room - now returns nil plus error message (as does other run-time errors) - previously would return just a nil on NO exit stubs but now returns a notification error message as well, to aide disambiguation of the nil value.
getExitStubs1
- stubs = getExitStubs1(roomid)
- Returns an indexed table (starting at 1) of the direction #'s that have an exit stub marked in them. You can use this information to connect earlier-made exit stubs between rooms when mapping. As this function starts indexing from 1 as it is default in Lua, you can use ipairs() to iterate over the results.
- See also
- getExitStubs()
- Example
-- show the exit stubs in room 6 as numbers
for k,v in ipairs(getExitStubs1(6)) do print(k,v) end
getExitWeights
- weights = getExitWeights(roomid)
- Returns a key-value table of the exit weights that a room has, with the direction or special exit as a key and the value as the exit weight. If a weight for a direction wasn't yet set, it won't be listed.
- Parameters
- roomid:
- Room ID to view the exit weights in.
- See also: setExitWeight()
getGridMode
- TrueOrFalse = getGridMode(areaID)
- Use this to see, if a specific area has grid/wilderness view mode set. This way, you can also calculate from a script, how many grid areas a map has got in total.

- Parameters
- areaID:
- Area ID (number) to view the grid mode of.
- See also: setGridMode()
- Example
getGridMode(55)
-- will return: false
setGridMode(55, true) -- set area with ID 55 to be in grid mode
getGridMode(55)
-- will return: true
getMapEvents
- mapevents = getMapEvents()
- Returns a list of map events currently registered. Each event is a dictionary with the keys uniquename, parent, event name, display name, and arguments, which correspond to the arguments of addMapEvent().
- See also: addMapMenu(), removeMapEvent(), addMapEvent()
- Example
addMapEvent("room a", "onFavorite") -- will make a label "room a" on the map menu's right click that calls onFavorite
addMapEvent("room b", "onFavorite", "Favorites", "Special Room!", 12345, "arg1", "arg2", "argn")
local mapEvents = getMapEvents()
for _, event in ipairs(mapEvents) do
echo(string.format("MapEvent '%s' is bound to event '%s' with these args: '%s'", event["uniquename"], event["event name"], table.concat(event["arguments"], ",")))
end

getMapLabel
- labelinfo = getMapLabel(areaID, labelID or labelText)
- Returns a key-value table describing that particular label in an area. Keys it contains are the X, Y, Z coordinates, Height and Width, BgColor, FgColor, Pixmap, and the Text it contains. If the label is an image label, then Text will be set to the no text string.
- BgColor and FgColor are tables with r,g,b keys, each holding 0-255 color component value.
- Pixmap is base64 encoded image of label.
Note: BgColor, FgColor, Pixmap are available in Mudlet 4.11+
- Parameters
- areaID: areaID from which to retrieve label
- labelID: labelID (getMapLabels return table key) or labelText (exact match)
See also: createMapLabel(), getMapLabels()
- Example
lua getMapLabels(52)
{
"no text",
[0] = "test"
}
lua getMapLabel(52, 0)
{
Y = -2,
X = -8,
Z = 11,
Height = 3.9669418334961,
Text = "test",
Width = 8.6776866912842,
BgColor = {
b = 0,
g = 0,
r = 0
},
FgColor = {
b = 50,
g = 255,
r = 255
},
Pixmap = "iVBORw0KG(...)lFTkSuQmCC" -- base64 encoded png image (shortened for brevity)
}
lua getMapLabel(52, "no text")
{
Y = 8,
X = -15,
Z = 11,
Height = 7.2520666122437,
Text = "no text"
Width = 11.21900844574,
BgColor = {
b = 0,
g = 0,
r = 0
},
FgColor = {
b = 50,
g = 255,
r = 255
},
Pixmap = "iVBORw0KG(...)lFTkSuQmCC" -- base64 encoded png image (shortened for brevity)
}
getMapLabels
- arealabels = getMapLabels(areaID)
- Returns an indexed table (that starts indexing from 0) of all of the labels in the area, plus their label text. You can use the label id to deleteMapLabel() it.
- If there are no labels in the area at all, it will return an empty table.
- See also: createMapLabel(), getMapLabel(), deleteMapLabel()
- Example
display(getMapLabels(43))
table {
0: ''
1: 'Waterways'
}
deleteMapLabel(43, 0)
display(getMapLabels(43))
table {
1: 'Waterways'
}
getMapMenus
- getMapMenus()
- Returns a table with the available map menus as key-value in the format of
map menu - parent item
. If an item is positioned at the menu's top-level, the value will saytop-level
. - If you haven't opened a map yet, getMapMenus() will return nil+error message. If you don't have any map labels yet, an empty table
{}
is returned.
- See also: addMapMenu(), addMapEvent()
- Example
-- given the following menu structure:
top-level
menu1
menu1.1
action1.1.1
menu1.2
action1.2.1
menu2
getMapMenus() -- will return:
{
menu2 = "top-level",
menu1.2 = "menu1",
menu1.1 = "menu1",
menu1 = "top-level"
}
getMapSelection
- getMapSelection()
- Returns a table containing details of the current mouse selection in the 2D mapper.
- Reports on one or more rooms being selected (i.e. they are highlighted in orange).
- The contents of the table will vary depending on what is currently selected. If the selection is of map rooms then there will be keys of center and rooms: the former will indicates the center room (the one with the yellow cross-hairs) if there is more than one room selected or the only room if there is only one selected (there will not be cross-hairs in that case); the latter will contain a list of the one or more rooms.
- Example - several rooms selected
display(getMapSelection())
{
center = 5013,
rooms = {
5011,
5012,
5013,
5014,
5018,
5019,
5020
}
}
- Example - one room selected
display(getMapSelection())
{
center = 5013,
rooms = {
5013
}
}
- Example - no or something other than a room selected
display(getMapSelection())
{
}

getMapUserData
- getMapUserData( key )
- Parameters
- key:
- string used as a key to select the data stored in the map as a whole.
- Returns the user data item (string); will return a nil+error message if there is no data with such a key in the map data.
- See also: getAllMapUserData(), setMapUserData()
- Example
display(getMapUserData("last updated"))
--might result in:--
"December 5, 2020"

getMapZoom
- getMapZoom([areaID])
- Gets the current 2D map zoom level. Added in Mudlet 4.17.0 also with the option to get the zoom for an area to be specified even if it is not the one currently being viewed. This change is combined with Mudlet remembering the zoom level last used for each area and with the revision of the setMapZoom() function to also take an areaID to work on instead of the current area being viewed in the map.
- See also: setMapZoom().

- Parameters
- areaID:
- Area ID number to get the 2D zoom for (optional, the function works on the area currently being viewed if this is omitted).
- Returns
- A floating point number on success
- nil and an error message on failure.
- Example
echo("\nCurrent zoom level: " .. getMapZoom() .. "\n")
-- Could be anything from 3 upwards:
Current zoom level: 42.4242
setMapZoom(2.5 + getMapZoom(1), 1) -- zoom out the area with ID 1 by 2.5
true
Note: The precise meaning of a particular zoom value may have an underlying meaning however that has not been determined other than that the minimum value is 3.0 and the initial value - and what prior Mudlet versions started each session with - is 20.0.
getPath
- getPath(roomID from, roomID to)
- Returns a boolean true/false if a path between two room IDs is possible. If it is, the global speedWalkDir table is set to all of the directions that have to be taken to get there, and the global speedWalkPath table is set to all of the roomIDs you'll encounter on the way, and as of 3.0, speedWalkWeight will return all of the room weights. Additionally returns the total cost (all weights added up) of the path after the boolean argument in 3.0.
- See also: translateTable()
- Example
-- check if we can go to room 155 from room 34 - if yes, go to it
if getPath(34,155) then
gotoRoom(155)
else
echo("\nCan't go there!")
end
getPlayerRoom
- getPlayerRoom()
- Returns the current player location as set by centerview().
- See also: centerview
- Example
display("We're currently in " .. getRoomName(getPlayerRoom()))

getRoomArea
- getRoomArea(roomID)
- Returns the area ID of a given room ID. To get the area name, you can check the area ID against the data given by getAreaTable() function, or use the getRoomAreaName() function.
Note: If the room ID does not exist, this function will raise an error.
- Example
display("Area ID of room #100 is: "..getRoomArea(100))
display("Area name for room #100 is: "..getRoomAreaName(getRoomArea(100)))
getRoomAreaName
- getRoomAreaName(areaID or areaName)
- Returns the area name for a given area id; or the area id for a given area name.
Note: Despite the name, this function will not return the area name for a given room id (or room name) directly. However, renaming or revising it would break existing scripts.
- Example
echo(string.format("room id #455 is in %s.", getRoomAreaName(getRoomArea(455))))
getRoomChar
- getRoomChar(roomID)
- Returns the single ASCII character that forms the symbol for the given room id.
- Since Mudlet version 3.8 : this facility has been extended:
- Returns the string (UTF-8) that forms the symbol for the given room id; this may have been set with either setRoomChar() or with the symbol (was letter in prior versions) context menu item for rooms in the 2D Map.
getRoomCharColor
- r,g,b = getRoomCharColor(roomID)
- Returns the color of the Room Character as a set of r,g,b color coordinates.
- See also
- setRoomCharColor(), getRoomChar()
- Parameters
- roomID:
- The room ID to get the room character color from
- Returns
- The color as 3 separate numbers, red, green, and blue from 0-255
- Example
-- gets the color of the room character set on room 12345. If no room character is set the default 'color' is 0,0,0
local r,g,b = getRoomCharColor(12345)
decho(f"Room Character for room 12345 is <{r},{g},{b}>this color.<r> It is made up of <{r},0,0>{r} red<r>, <0,{g},0>{g} green<r>, <0,0,{b}> {b} blue<r>.\")
getRoomCoordinates
- x,y,z = getRoomCoordinates(roomID)
- Returns the room coordinates of the given room ID.
- Example
local x,y,z = getRoomCoordinates(roomID)
echo("Room Coordinates for "..roomID..":")
echo("\n X:"..x)
echo("\n Y:"..y)
echo("\n Z:"..z)
-- A quick function that will find all rooms on the same z-position in an area; this is useful if, say, you want to know what all the same rooms on the same "level" of an area is.
function sortByZ(areaID, zval)
local area = getAreaRooms(areaID)
local t = {}
for _, id in ipairs(area) do
local _, _, z = getRoomCoordinates(id)
if z == zval then
table.insert(t, id)
end
end
return t
end
getRoomEnv
- envID = getRoomEnv(roomID)
- Returns the environment ID of a room. The mapper does not store environment names, so you'd need to keep track of which ID is what name yourself.
- Example
function checkID(id)
echo(string.format("The env ID of room #%d is %d.\n", id, getRoomEnv(id)))
end
getRoomExits
- getRoomExits (roomID)
- Returns the currently known non-special exits for a room in an key-index form: exit = exitroomid.
- See also: getSpecialExits()
- Example
table {
'northwest': 80
'east': 78
}
Here's a practical example that queries the rooms around you and searched for one of the water environments (the number would depend on how it was mapped):
local exits = getRoomExits(mycurrentroomid)
for direction,num in pairs(exits) do
local env_num = getRoomEnv(num)
if env_num == 22 or env_num == 20 or env_num == 30 then
print("There's water to the "..direction.."!")
end
end
getRoomHashByID
- getRoomHashByID(roomID)
- Returns a room hash that is associated with a given room ID in the mapper. This is primarily for games that make use of hashes instead of room IDs. It may be used to share map data while not sharing map itself. nil is returned if no room is not found.
- See also: getRoomIDbyHash()

- Example
for id,name in pairs(getRooms()) do
local h = getRoomUserData(id, "herbs")
if h ~= "" then
echo(string.format([[["%s"] = "%s",]], getRoomHashByID(id), h))
echo("\n")
end
end
getRoomIDbyHash
- roomID = getRoomIDbyHash(hash)
- Returns a room ID that is associated with a given hash in the mapper. This is primarily for games that make use of hashes instead of room IDs (like Avalon.de). -1 is returned if no room ID matches the hash.
- See also: getRoomHashByID()
- Example
-- example taken from http://forums.mudlet.org/viewtopic.php?f=13&t=2177
local id = getRoomIDbyHash("5dfe55b0c8d769e865fd85ba63127fbc")
if id == -1 then
id = createRoomID()
setRoomIDbyHash(id, "5dfe55b0c8d769e865fd85ba63127fbc")
addRoom(id)
setRoomCoordinates(id, 0, 0, -1)
end
getRoomName
- getRoomName(roomID)
- Returns the room name for a given room id.
- Example
echo(string.format("The name of the room id #455 is %s.", getRoomName(455))
getRooms
- rooms = getRooms()
- Returns the list of all rooms in the map in the whole map in roomid - room name format.
- Example
-- simple, raw viewer for rooms in the world
display(getRooms())
-- iterate over all rooms in code
for id,name in pairs(getRooms()) do
print(id, name)
end
getRoomsByPosition
- roomTable = getRoomsByPosition(areaID, x,y,z)
- Returns an indexed table of all rooms at the given coordinates in the given area, or an empty one if there are none. This function can be useful for checking if a room exists at certain coordinates, or whenever you have rooms overlapping.
Note: The returned table starts indexing from 0 and not the usual lua index of 1, which means that using # to count the size of the returned table will produce erroneous results - use table.size() instead.
- Example
-- sample alias to determine a room nearby, given a relative direction from the current room
local otherroom
if matches[2] == "" then
local w = matches[3]
local ox, oy, oz, x,y,z = getRoomCoordinates(mmp.currentroom)
local has = table.contains
if has({"west", "left", "w", "l"}, w) then
x = (x or ox) - 1; y = (y or oy); z = (z or oz)
elseif has({"east", "right", "e", "r"}, w) then
x = (x or ox) + 1; y = (y or oy); z = (z or oz)
elseif has({"north", "top", "n", "t"}, w) then
x = (x or ox); y = (y or oy) + 1; z = (z or oz)
elseif has({"south", "bottom", "s", "b"}, w) then
x = (x or ox); y = (y or oy) - 1; z = (z or oz)
elseif has({"northwest", "topleft", "nw", "tl"}, w) then
x = (x or ox) - 1; y = (y or oy) + 1; z = (z or oz)
elseif has({"northeast", "topright", "ne", "tr"}, w) then
x = (x or ox) + 1; y = (y or oy) + 1; z = (z or oz)
elseif has({"southeast", "bottomright", "se", "br"}, w) then
x = (x or ox) + 1; y = (y or oy) - 1; z = (z or oz)
elseif has({"southwest", "bottomleft", "sw", "bl"}, w) then
x = (x or ox) - 1; y = (y or oy) - 1; z = (z or oz)
elseif has({"up", "u"}, w) then
x = (x or ox); y = (y or oy); z = (z or oz) + 1
elseif has({"down", "d"}, w) then
x = (x or ox); y = (y or oy); z = (z or oz) - 1
end
local carea = getRoomArea(mmp.currentroom)
if not carea then mmp.echo("Don't know what area are we in.") return end
otherroom = select(2, next(getRoomsByPosition(carea,x,y,z)))
if not otherroom then
mmp.echo("There isn't a room to the "..w.." that I see - try with an exact room id.") return
else
mmp.echo("The room "..w.." of us has an ID of "..otherroom)
end
getRoomUserData
- getRoomUserData(roomID, key)
- Returns the user data value (string) stored at a given room with a given key (string), or "" if none is stored. Use setRoomUserData() function for setting the user data.
- Example
display(getRoomUserData(341, "visitcount"))
- getRoomUserData(roomID, key, enableFullErrorReporting)
- Returns the user data value (string) stored at a given room with a given key (string), or, if the boolean value enableFullErrorReporting is true, nil and an error message if the key is not present or the room does not exist; if enableFullErrorReporting is false an empty string is returned but then it is not possible to tell if that particular value is actually stored or not against the given key.
- See also: clearRoomUserData(), clearRoomUserDataItem(), getAllRoomUserData(), getRoomUserDataKeys(), searchRoomUserData(), setRoomUserData()
- Example
local vNum = 341
result, errMsg = getRoomUserData(vNum, "visitcount", true)
if result ~= nil then
display(result)
else
echo("\nNo visitcount data for room: "..vNum.."; reason: "..errMsg.."\n")
end
getRoomUserDataKeys
- getRoomUserDataKeys(roomID)
- Returns all the keys for user data items stored in the given room ID; will return an empty table if there is no data stored or nil if there is no such room with that ID. Can be useful if the user was not the one who put the data in the map in the first place!
- See also: clearRoomUserData(), clearRoomUserDataItem(), getAllRoomUserData(), getRoomUserData(), searchRoomUserData(), setRoomUserData()
- Example
display(getRoomUserDataKeys(3441))
--might result in:--
{
"description",
"doorname_up",
}

getRoomWeight
- getRoomWeight(roomID)
- Returns the weight of a room. By default, all new rooms have a weight of 1.
- See also: setRoomWeight()
- Example
display("Original weight of room 541: "..getRoomWeight(541))
setRoomWeight(541, 3)
display("New weight of room 541: "..getRoomWeight(541))
getSpecialExits
- exits = getSpecialExits(roomID[, listAllExits])
- Parameters
- roomID:
- Room ID to return the special exits of.
- listAllExits:
- (Since TBA) In the case where there is more than one special exit to the same room ID list all of them.
- Returns a roomid table of sub-tables containing name/command and exit lock status, of the special exits in the room. If there are no special exits in the room, the table returned will be empty.
- Before TBA (likely to be Mudlet version 4.11.0), if more than one special exit goes to the same exit room id then one of those exits is returned at random. Since TBA this will be the best (i.e. lowest-weight) exit that is not locked; should none be unlocked then the lowest locked one will be listed. In case of a tie, one of the tying exits will be picked at random.
- See also: getRoomExits()
- Example
-- There are three special exits from 1337 to the room 42:
-- "climb down ladder" which is locked and has an exit weight of 10
-- "step out window" which is unlocked and has an exit weight of 20
-- "jump out window" which is unlocked and has an exit weight of 990
getSpecialExits(1337)
-- In 4.10.1 and before this could results in:
table {
42 = {"jump out window" = "0"},
666 = {"dive into pit" = "1"}
}
-- OR
table {
42 = {"climb down ladder" = "1"},
666 = {"dive into pit" = "1"}
}
-- OR
table {
42 = {"step out window" = "0"},
666 = {"dive into pit" = "1"}
}
-- From TBA this will return:
table {
42 = {"step out window" = "0"},
666 = {"dive into pit" = "1"}
}
-- From TBA, with the second argument as true, this gives:
getSpecialExits(1337, true)
table {
42 = {"step out window" = "0",
"climb down ladder" = "1",
"jump out window" = "0"},
666 = {"dive into pit" = "1"}
}
getSpecialExitsSwap
- getSpecialExitsSwap(roomID)
- Very similar to getSpecialExits() function, but returns the rooms in the command - roomid style.
gotoRoom
- gotoRoom (roomID)
- Speedwalks you to the given room from your current room if it is able and knows the way. You must turn the map on for this to work, else it will return "(mapper): Don't know how to get there from here :(".
In case this isn't working, and you are coding your own mapping script, see here how to implement additional functionality necessary.
hasExitLock
- status = hasExitLock(roomID, direction)
- Returns true or false depending on whenever a given exit leading out from a room is locked. Direction can be specified as a number, short direction name ("nw") or long direction name ("northwest").
- Example
-- check if the east exit of room 1201 is locked
display(hasExitLock(1201, 4))
display(hasExitLock(1201, "e"))
display(hasExitLock(1201, "east"))
- See also: lockExit()
hasSpecialExitLock
- hasSpecialExitLock(from roomID, to roomID, moveCommand)
- Returns true or false depending on whenever a given exit leading out from a room is locked. moveCommand is the action to take to get through the gate.
See also: lockSpecialExit()
-- lock a special exit from 17463 to 7814 that uses the 'enter feather' command
lockSpecialExit(17463, 7814, 'enter feather', true)
-- see if it is locked: it will say 'true', it is
display(hasSpecialExitLock(17463, 7814, 'enter feather'))
highlightRoom
- highlightRoom( roomID, color1Red, color1Green, color1Blue, color2Red, color2Green, color2Blue, highlightRadius, color1Alpha, color2Alpha)
- Highlights a room with the given color, which will override its environment color. If you use two different colors, then there'll be a shading from the center going outwards that changes into the other color.
- Parameters
- roomID
- ID of the room to be colored.
- color1Red, color1Green, color1Blue
- RGB values of the first color.
- color2Red, color2Green, color2Blue
- RGB values of the second color.
- highlightRadius
- The radius for the highlight circle - if you don't want rooms beside each other to overlap, use 1 as the radius.
- color1Alpha and color2Alpha
- Transparency values from 0 (completely transparent) to 255 (not transparent at all).
- See also: unHighlightRoom()
-- color room #351 red to blue
local r,g,b = unpack(color_table.red)
local br,bg,bb = unpack(color_table.blue)
highlightRoom(351, r,g,b,br,bg,bb, 1, 255, 255)
killMapInfo
- killMapInfo(label)
Delete a map info contributor entirely - it will be not available anymore.
- Parameters
- label:
- Name under which map info to be removed was registered.
- See also: registerMapInfo(), enableMapInfo(), disableMapInfo()

loadJsonMap
- loadJsonMap(pathFileName)
- Parameters
- pathFileName a string that is an absolute path and file name to read the data from.
Load the Mudlet map in text (JSON) format. It does take longer than loading usual map file (.dat in binary) so it will show a progress dialog.
- See also: saveJsonMap()
Returns:
- true on success
- nil and an error message on failure.
- Example
loadJsonMap(getMudletHomeDir() .. "/map.json")
true

loadMap
- loadMap(file location)
- Loads the map file from a given location. The map file must be in Mudlet's format - saved with saveMap() or, as of the Mudlet 3.0 may be a MMP XML map conforming to the structure used by I.R.E. for their downloadable maps for their MUD games.
- Returns a boolean for whenever the loading succeeded. Note that the mapper must be open, or this will fail.
- Using no arguments will load the last saved map.
loadMap("/home/user/Desktop/Mudlet Map.dat")
Note: A file name ending with
.xml
will indicate the XML format.
lockExit
- lockExit(roomID, direction, lockIfTrue)
- Locks a given exit from a room. The destination may remain accessible through other paths, unlike lockRoom. Direction can be specified as a number, short direction name ("nw") or long direction name ("northwest").
- See also: hasExitLock()
- Example
-- lock the east exit of room 1201 so we never path through it
lockExit(1201, 4, true)
lockRoom
- lockRoom (roomID, lockIfTrue)
- Locks a given room id from future speed walks (thus the mapper will never path through that room).
- See also: roomLocked()
- Example
lockRoom(1, true) -- locks a room if from being walked through when speedwalking.
lockRoom(1, false) -- unlocks the room, adding it back to possible rooms that can be walked through.
lockSpecialExit
- lockSpecialExit (from roomID, to roomID, special exit command, lockIfTrue)
- Locks a given special exit, leading from one specific room to another that uses a certain command from future speed walks (thus the mapper will never path through that special exit).
- See also: hasSpecialExitLock(), lockExit(), lockRoom()
- Example
lockSpecialExit(1,2,'enter gate', true) -- locks the special exit that does 'enter gate' to get from room 1 to room 2
lockSpecialExit(1,2,'enter gate', false) -- unlocks the said exit
moveMapWidget
- moveMapWidget(Xpos, Ypos)
- moves the map window to the given position.
- See also: openMapWidget(), closeMapWidget(), resizeMapWidget()
- Parameters
- Xpos:
- X position of the map window. Measured in pixels, with 0 being the very left. Passed as an integer number.
- Ypos:
- Y position of the map window. Measured in pixels, with 0 being the very top. Passed as an integer number.

openMapWidget
- openMapWidget([dockingArea | Xpos, Ypos, width, height])
means either of these are fine:
- openMapWidget()
- openMapWidget(dockingArea)
- openMapWidget(Xpos, Ypos, width, height)
- opens a map window with given options.
- See also: closeMapWidget(), moveMapWidget(), resizeMapWidget()

- Parameters
Note: If no parameter is given the map window will be opened with the saved layout or at the right docking position (similar to clicking the icon)
- dockingArea:
- If only one parameter is given this parameter will be a string that contains one of the possible docking areas the map window will be created in (f" floating "t" top "b" bottom "r" right and "l" left)
Note: If 4 parameters are given the map window will be created in floating state
- Xpos:
- X position of the map window. Measured in pixels, with 0 being the very left. Passed as an integer number.
- Ypos:
- Y position of the map window. Measured in pixels, with 0 being the very left. Passed as an integer number.
- width:
- The width map window, in pixels. Passed as an integer number.
- height:
- The height map window, in pixels. Passed as an integer number.
pauseSpeedwalk
- pauseSpeedwalk()
- Pauses a speedwalk started using speedwalk()
- See also: speedwalk(), stopSpeedwalk(), resumeSpeedwalk()

local ok, err = pauseSpeedwalk()
if not ok then
debugc(f"Error: unable to pause speedwalk because {err}\n")
return
end
registerMapInfo
- registerMapInfo(label, function)
Adds an extra 'map info' to the mapper widget which can be used to display custom information.
- See also: killMapInfo(), enableMapInfo(), disableMapInfo()

Note:
You can register multiple map infos - just give them unique names and toggle whichever ones you need.
- Parameters
- label:
- Name under which map info will be registered and visible in select box under mapper. You can use it later to kill map info, enable it, disable it or overwrite using registerMapInfo() again.
- function:
- Callback function that will be responsible for returning information how to draw map info fragment.
Callback function is called with following arguments:
- roomId - current roomId or currently selected room (when multiple selection is made this is center room)
- selectionSize - how many rooms are selected
- areaId - roomId's areaId
- displayedAreaId - areaId that is currently displayed
Callback needs to return following:
- text - text that will be displayed (when empty, nothing will be displayed, if you want to "reserve" line or lines use not empty value " " or add line breaks "\n")
- isBold (optional) - true/false - determines whether text will be bold
- isItalic (optional) - true/false - determines whether text will be italic
- color r (optional) - color of text red component (0-255)
- color g (optional) - color of text green component (0-255)
- color b (optional) - color of text blue component (0-255)
Note:
Map info is registered in disabled state, you need to enable it through script or by selecting checkbox under mapper.
registerMapInfo("My very own handler!", function(roomId, selectionSize, areaId, displayedArea)
return string.format("RoomId: %d\nNumbers of room selected: %d\nAreaId: %d\nDisplaying area: %d", roomId, selectionSize, areaId, displayedArea),
true, true, 0, 255, 0
end)
enableMapInfo("My very own handler!")
Example will display something like that:
Using function arguments is completely optional and you can determine whether and how to display map info completely externally.
registerMapInfo("Alert", function()
if character.hp < 20 then
return "Look out! Your HP is getting low", true, false, unpack(color_table.red) -- will display red, bolded warning whne character.hp is below 20
else
return "" -- will not return anything
end
end)
enableMapInfo("Alert")
resumeSpeedwalk
- resumeSpeedwalk()
- Continues a speedwalk paused using pauseSpeedwalk()
- See also: speedwalk(), pauseSpeedwalk(), stopSpeedwalk()

local ok, err = resumeSpeedwalk()
if not ok then
cecho(f"\n<red>Error:<reset> Problem resuming speedwalk: {err}\n")
return
end
cecho("\n<green>Successfully resumed speedwalk!\n")
removeCustomLine
- removeCustomLine(roomID, direction)
- Removes the custom exit line that's associated with a specific exit of a room.
- See also: addCustomLine(), getCustomLines()
- Example
-- remove custom exit line that starts in room 315 going north
removeCustomLine(315, "n")
removeMapEvent
- removeMapEvent(event name)
- Removes the given menu entry from a mappers right-click menu. You can add custom ones with addMapEvent().
- See also: addMapEvent(), getMapEvents(), removeMapMenu()
- Example
addMapEvent("room a", "onFavorite") -- add one to the general menu
removeMapEvent("room a") -- removes the said menu
removeMapMenu
- removeMapMenu(menu name)
- Removes the given submenu from a mappers right-click menu. You can add custom ones with addMapMenu().
- See also: addMapMenu(), getMapMenus(), removeMapEvent()
- Example
addMapMenu("Test") -- add submenu to the general menu
removeMapMenu("Test") -- removes that same menu again
removeSpecialExit
- removeSpecialExit(roomID, command)
- Removes the special exit which is accessed by command from the room with the given roomID.
- See also: addSpecialExit(), clearSpecialExits()
- Example
addSpecialExit(1, 2, "pull rope") -- add a special exit from room 1 to room 2
removeSpecialExit(1, "pull rope") -- removes the exit again
resetRoomArea
- resetRoomArea (roomID)
- Unassigns the room from its given area. While not assigned, its area ID will be -1. Note that since Mudlet 3.0 the "default area" which has the id of -1 may be selectable in the area selection widget on the mapper - although there is also an option to conceal this in the settings.
- See also: setRoomArea(), getRoomArea()
- Example
resetRoomArea(3143)
resizeMapWidget
- resizeMapWidget(width, height)
- resizes a map window with given width, height.
- See also: openMapWidget(), closeMapWidget(), moveMapWidget()

- Parameters
- width:
- The width of the map window, in pixels. Passed as an integer number.
- height:
- The height of the map window, in pixels. Passed as an integer number.
roomExists
- roomExists(roomID)
- Returns a boolean true/false depending if the room with that ID exists (is created) or not.
roomLocked
- locked = roomLocked(roomID)
- Returns true or false whenever a given room is locked.
- See also: lockRoom()
- Example
echo(string.format("Is room #4545 locked? %s.", roomLocked(4545) and "Yep" or "Nope"))
saveJsonMap
- saveJsonMap([pathFileName])
Saves all the data that is normally held in the Mudlet map (.dat as a binary format) in text (JSON) format. It does take longer to do this, so a progress dialog will be shown indicating the status.
- See also: loadJsonMap()

- Parameters
- pathFileName (optional in Mudlet 4.12+): a string that is an absolute path and file name to save the data into.
- Returns
- true on success
- nil and an error message on failure.
- Example
saveJsonMap(getMudletHomeDir() .. "/map.json")
true
saveMap
- saveMap([location], [version])
- Saves the map to a given location, and returns true on success. The location folder needs to be already created for save to work. You can also save the map in the Mapper settings tab.
- Parameters
- location
- (optional) save the map to the given location if provided, or the default one otherwise.
- version
- (optional) map version as a number to use when saving (Mudlet 3.17+)
- See also: loadMap()
- Example
local savedok = saveMap(getMudletHomeDir().."/my fancy map.dat")
if not savedok then
echo("Couldn't save :(\n")
else
echo("Saved fine!\n")
end
-- save with a particular map version
saveMap(20)
searchAreaUserData
- searchAreaUserData(area number | area name[, case-sensitive [, exact-match]])
- Searches Areas' User Data in a manner exactly the same as searchRoomUserData() does in all Rooms' User Data, refer to that command for the specific details except to replace references to rooms and room ID numbers there with areas and areas ID numbers.
searchRoom
- searchRoom (room number | room name[, case-sensitive [, exact-match]])
- Searches for rooms that match (by case-insensitive, substring match) the given room name. It returns a key-value table in form of roomid = roomname, the optional second and third boolean parameters have been available since Mudlet 3.0;
- If no rooms are found, then an empty table is returned.
- If you pass it a number instead of a string as just one argument, it'll act like getRoomName() and return the room name.
- Examples
-- show the behavior when given a room number:
display(searchRoom(3088))
"The North Road South of Taren Ferry"
-- show the behavior when given a string:
-- shows all rooms containing the text in any case:
display(searchRoom("North road"))
{
[3114] = "Bend in North road",
[3115] = "North road",
[3116] = "North Road",
[3117] = "North road",
[3146] = "Bend in the North Road",
[3088] = "The North Road South of Taren Ferry",
[6229] = "Grassy Field By North Road"
}
-- or:
-- display(searchRoom("North road",false))
-- display(searchRoom("North road",false,false))
-- would both also produce those results.
-- shows all rooms containing the text in ONLY the letter-case provided:
display(searchRoom("North road",true,false))
{
[3114] = "Bend in North road",
[3115] = "North road",
[3117] = "North road",
}
-- shows all rooms containing ONLY that text in either letter-case:
lua searchRoom("North road",false,true)
{
[3115] = "North road",
[3116] = "North Road",
[3117] = "North road"
}
-- shows all rooms containing only and exactly the given text:
lua searchRoom("North road",true,true)
{
[3115] = "North road",
[3117] = "North road"
}
Note: Technically, with both options (case-sensitive and exact-match) set to true, one could just return a list of numbers as we know precisely what the string will be, but it was kept the same for maximum flexibility in user scripts.
searchRoomUserData
- searchRoomUserData([key, [value]])
- A command with three variants that search though all the rooms in sequence (so not as fast as a user built/maintained index system) and find/reports on the room user data stored:
- See also: clearRoomUserData(), clearRoomUserDataItem(), getAllRoomUserData(), getRoomUserData(), getRoomUserDataKeys(), setRoomUserData()
- searchRoomUserData(key, value)
- Reports a (sorted) list of all room ids with user data with the given "value" for the given (case sensitive) "key".
- searchRoomUserData(key)
- Reports a (sorted) list of the unique values from all rooms with user data with the given (case sensitive) "key".
- searchRoomUserData()
- Reports a (sorted) list of the unique keys from all rooms with user data with any (case sensitive) "key", available since Mudlet 3.0. It is possible (though not recommended) to have a room user data item with an empty string "" as a key, this is handled correctly.

- Examples
-- if I had stored the details of "named doors" as part of the room user data --
display(searchRoomUserData("doorname_up"))
--[[ could result in a list:
{
"Eastgate",
"Northgate",
"boulderdoor",
"chamberdoor",
"dirt",
"floorboards",
"floortrap",
"grate",
"irongrate",
"rockwall",
"tomb",
"trap",
"trapdoor"
}]]
-- then taking one of these keys --
display(searchRoomUserData("doorname_up","trapdoor"))
--[[ might result in a list:
{
3441,
6113,
6115,
8890
}
]]
setAreaName
- setAreaName(areaID or areaName, newName)
- Names, or renames an existing area to the new name. The area must be created first with addAreaName() and it must be unique.
Note: parameter areaName is available since Mudlet 3.0.
- See also: deleteArea(), addAreaName()
- Example
setAreaName(2, "My city")
-- available since Mudlet 3.0
setAreaName("My old city name", "My new city name")
setAreaUserData
- setAreaUserData(areaID, key (as a string), value (as a string))
- Stores information about an area under a given key. Similar to Lua's key-value tables, except only strings may be used here. One advantage of using userdata is that it's stored within the map file itself - so sharing the map with someone else will pass on the user data. Returns a lua true value on success. You can have as many keys as you'd like, however a blank key will not be accepted and will produce a lua nil and an error message instead.
- Returns true if successfully set.
- See also: clearAreaUserData(), clearAreaUserDataItem(), getAllAreaUserData(), getAreaUserData(), searchAreaUserData()

- Example
-- can use it to store extra area details...
setAreaUserData(34, "country", "Andor.")
-- or a sound file to play in the background (with a script that checks a room's area when entered)...
setAreaUserData(34, "backgroundSound", "/home/user/mudlet-data/soundFiles/birdsong.mp4")
-- can even store tables in it, using the built-in yajl.to_string function
setAreaUserData(101, "some table", yajl.to_string({ruler = "Queen Morgase Trakand", clan = "Lion Warden"}))
display("The ruler's name is: "..yajl.to_value(getRoomUserData(101, "some table")).ruler)
setCustomEnvColor
- setCustomEnvColor(environmentID, r,g,b,a)
- Creates, or overrides an already created custom color definition for a given environment ID. Note that this will not work on the default environment colors - those are adjustable by the user in the preferences. You can however create your own environment and use a custom color definition for it.
- See also: getCustomEnvColorTable(), setRoomEnv()
Note: Numbers 1-16 and 257-272 are reserved by Mudlet. 257-272 are the default colors the user can adjust in mapper settings, so feel free to use them if you'd like - but don't overwrite them with this function.
- Example
setRoomEnv(571, 200) -- change the room's environment ID to something arbitrary, like 200
local r,g,b = unpack(color_table.blue)
setCustomEnvColor(200, r,g,b, 255) -- set the color of environmentID 200 to blue
setDoor
- setDoor(roomID, exitCommand, doorStatus)
- Creates or deletes a door in a room. Doors are purely visual - they don't affect pathfinding. You can use the information to adjust your speedwalking path based on the door information in a room, though.
- Doors CAN be set on stub exits - so that map makers can note if there is an obvious door to somewhere even if they do not (yet) know where it goes, perhaps because they do not yet have the key to open it!
- Returns true if the change could be made, false if the input was valid but ineffective (door status was not changed), and nil with a message string on invalid input (value type errors).
- See also: getDoors()
- Parameters
- roomID:
- Room ID to to create the door in.
- exitCommand:
- The cardinal direction for the door is in - it can be one of the following: n, e, s, w, ne, se, sw, ne. {Plans are afoot to add support for doors on the other normal exits: up, down, in and out, and also on special exits - though more work will be needed for them to be shown in the mapper.} It is important to ONLY use these direction codes as others e.g. "UP" will be accepted - because a special exit could have ANY name/lua script - but it will not be associated with the particular normal exit - recent map auditing code about to go into the code base will REMOVE door and other room exit items for which the appropriate exit (or stub) itself is not present, so in this case, in the absence of a special exit called "UP" that example door will not persist and not show on the normal "up" exit when that is possible later on.
- doorStatus:
- The door status as a number - 0 means no (or remove) door, 1 means open door (will draw a green square on exit), 2 means closed door (yellow square) and 3 means locked door (red square).
- Example
-- make a door on the east exit of room 4234 that is currently open
setDoor(4234, 'e', 1)
-- remove a door from room 923 that points north
setDoor(923, 'n', 0)
setExit
- setExit(from roomID, to roomID, direction)
- Creates a one-way exit from one room to another using a standard direction - which can be either one of n, ne, nw, e, w, s, se, sw, u, d, in, out, the long version of a direction, or a number which represents a direction. If there was an exit stub in that direction already, then it will be automatically deleted for you.
- Returns false if the exit creation didn't work.
- See also: addSpecialExit()
- Example
-- alias pattern: ^exit (\d+) (\d+) (\w+)$
-- so exit 1 2 5 will make an exit from room 1 to room 2 via north
if setExit(tonumber(matches[2]), tonumber(matches[3]), matches[4]) then
echo("\nExit set to room:"..matches[3].." from "..matches[2]..", direction:"..string.upper(matches[3]))
else
echo("Failed to set the exit.\n")
end
This function can also delete exits from a room if you use it like so:
setExit(from roomID, -1, direction)
- which will delete an outgoing exit in the specified direction from a room.
setExitStub
- setExitStub(roomID, direction, set/unset)
Creates or removes an exit stub from a room in a given directions. You can use exit stubs later on to connect rooms that you're sure of are together. Exit stubs are also shown visually on the map, so the mapper can easily tell which rooms need finishing.
- Parameters
- roomID:
- The room to place an exit stub in, as a number.
- direction:
- The direction the exit stub should lead in - as a short direction name ("nw"), long direction name ("northwest") or a number.
- set/unset:
- A boolean to create or delete the exit stub.
- See also: getExitStubs(), connectExitStub()
- Example
Create an exit stub to the south from room 8:
setExitStub(8, "s", true)
How to delete all exit stubs in a room:
for i,v in pairs(getExitStubs(roomID)) do
setExitStub(roomID, v,false)
end
setExitWeight
- setExitWeight(roomID, exitCommand, weight)
- Gives an exit a weight, which makes it less likely to be chosen for pathfinding. All exits have a weight of 0 by default, which you can increase. Exit weights are set one-way on an exit - if you'd like the weight to be applied both ways, set it from the reverse room and direction as well.
- Parameters
- roomID:
- Room ID to to set the weight in.
- exitCommand:
- The direction for the exit is in - it can be one of the following: n, ne, e, se, s, sw, w, nw, up, down, in, out, or, if it's a special exit, the special exit command - note that the strings for normal exits are case-sensitive and must currently be exactly as given here.
- weight:
- Exit weight - by default, all exits have a weight of 0 meaning that the weight of the destination room is use when the route finding code is considering whether to use that exit; setting a value for an exit can increase or decrease the chance of that exit/destination room being used for a route by the route-finding code. For example, if the destination room has very high weight compared to it's neighbors but the exit has a low value then that exit and thus the room is more likely to be used than if the exit was not weighted.
- See also: getExitWeights()
setGridMode
- setGridMode(areaID, true/false)
- Enables grid/wilderness view mode for an area - this will cause the rooms to lose their visible exit connections, like you'd see on compressed ASCII maps, both in 2D and 3D view mode; for the 2D map the custom exit lines will also not be shown if this mode is enabled.
- Returns true if the area exists, otherwise false.
- See also: getGridMode()
- Example
setGridMode(55, true) -- set area with ID 55 to be in grid mode
setMapUserData
- setMapUserData(key (as a string), value (as a string))
- Stores information about the map under a given key. Similar to Lua's key-value tables, except only strings may be used here. One advantage of using userdata is that it's stored within the map file itself - so sharing the map with someone else will pass on the user data. You can have as many keys as you'd like.
- Returns true if successfully set.
- See also: clearMapUserData(), clearMapUserDataItem(), getAllMapUserData(), getMapUserData()
- Example
-- store general meta information about the map...
setMapUserData("game_name", "Achaea Mudlet map")
-- or who the author was
setMapUserData("author", "Bob")
-- can even store tables in it, using the built-in yajl.to_string function
setMapUserData("some table", yajl.to_string({game = "mud.com", port = 23}))
display("Available game info in the map: ")
display(yajl.to_value(getMapUserData("some table")))
setMapZoom
- setMapZoom(zoom[, areaID])
- Zooms the 2D (only) map to a given zoom level. Larger numbers zooms the map further out. Revised in Mudlet 4.17.0 to allow the zoom for an area to be specified even if it is not the one currently being viewed. This change is combined with Mudlet permanently remembering (it is saved within the map file) the zoom level last used for each area and with the addition of the getMapZoom() function.
- See also: getMapZoom().
- Parameters
- zoom:
- floating point number that is at least 3.0 to set the zoom to.
- areaID:
- (Optional and only since Mudlet 4.17.0) Area ID number to adjust the 2D zoom for (optional, the function works on the area currently being viewed if this is omitted).
- Returns (only since Mudlet 4.17.0)
- true on success
- nil and an error message on failure.
- Example
setMapZoom(10.0) -- zoom to a somewhat acceptable level, a bit big but easily visible connections
true
setMapZoom(2.5 + getMapZoom(1), 1) -- zoom out the area with ID 1 by 2.5
true
Note: The precise meaning of a particular zoom value may have an underlying meaning however that has not been determined other than that the minimum value is 3.0 and the initial value - and what prior Mudlet versions started each session with - is 20.0.
setRoomArea
- setRoomArea(roomID, newAreaID or newAreaName)
- Assigns the given room to a new or different area. If the area is displayed in the mapper this will have the room be visually moved into the area as well.
- See also: resetRoomArea()
setRoomChar
- setRoomChar(roomID, character)
- Originally designed for an area in grid mode, takes a single ASCII character and draws it on the rectangular background of the room in the 2D map. In versions prior to Mudlet 3.8, the symbol can be cleared by using "_" as the character. In Mudlet version 3.8 and higher, the symbol may be cleared with either a space
" "
or an empty string""
.
- Game-related symbols for your map
- toddfast's font - 3000+ scalable vector RPG icons from game-icons.net, as well as a script to download the latest icons and generate a new font.
- Pixel Kitchen's Donjonikon Font - 10x10 fantasy and RPG-related icons.
- Example
setRoomChar(431, "#")
setRoomChar(123, "$")
-- emoji's work fine too, and if you'd like it coloured, set the font to Nojo Emoji in settings
setRoomChar(666, "👿")
- Since Mudlet version 3.8 : this facility has been extended:
- This function will now take a short string of any printable characters as a room symbol, and they will be shrunk to fit them all in horizontally but if they become too small that symbol may not be shown if the zoom is such that the room symbol is too small to be legible.
- As "_" is now a valid character an existing symbol may be erased with either a space " " or an empty string "" although neither may be effective in some previous versions of Mudlet.
- Should the rooms be set to be drawn as circles this is now accommodated and the symbol will be resized to fit the reduce drawing area this will cause.
- The range of characters that are available are now dependent on the fonts present in the system and a setting on the "Mapper" tab in the preferences that control whether a specific font is to be used for all symbols (which is best if a font is included as part of a game server package, but has the issue that it may not be displayable if the user does not have that font or chooses a different one) or any font in the user's system may be used (which is the default, but may not display the glyph {the particular representation of a grapheme in a particular font} that the original map creator expected). Should it not be possible to display the wanted symbol in the map because one or more of the required glyphs are not available in either the specified or any font depending on the setting then the replacement character (Unicode code-point U+FFFD '�') will be shown instead. To allow such missing symbols to be handled the "Mapper" tab on the preferences dialogue has an option to display:
- an indicator to show whether the symbol can be made just from the selected font (green tick), from the fonts available in the system (yellow warning triangle) or not at all (red cross)
- all the symbols used on the map and how they will be displayed both only using the selected font and all fonts
- the sequence of code-points used to create the symbol which will be useful when used in conjunction with character selection utilities such as charmap.exe on Windows and gucharmap on unix-like system
- a count of the rooms using the particular symbol
- a list, limited in entries of the first rooms using that symbol
- The font that is chosen to be used as the primary (or only) one for the room symbols is stored in the Mudlet map data so that setting will be included if a binary map is shared to other Mudlet users or profiles on the same system.
- See also: getRoomChar()
setRoomCharColor
- setRoomCharColor(roomId, r, g, b)
- Parameters
- roomID:
- Room ID to to set char color to.
- r:
- Red component of room char color (0-255)
- g:
- Green component of room char color (0-255)
- b:
- Blue component of room char color (0-255)
Sets color for room symbol.
setRoomCharColor(2402, 255, 0, 0)
setRoomCharColor(2403, 0, 255, 0)
setRoomCharColor(2404, 0, 0, 255)

- See also: unsetRoomCharColor()
setRoomCoordinates
- setRoomCoordinates(roomID, x, y, z)
- Sets the given room ID to be at the following coordinates visually on the map, where z is the up/down level. These coordinates are define the location of the room within a particular area (so not globally on the overall map).
Note: 0,0,0 is the center of the map.
- Examples
-- alias pattern: ^set rc (-?\d+) (-?\d+) (-?\d+)$
-- this sets the current room to the supplied coordinates
setRoomCoordinates(roomID,x,y,z)
centerview(roomID)
- You can make them relative asa well:
-- alias pattern: ^src (\w+)$
local x,y,z = getRoomCoordinates(previousRoomID)
local dir = matches[2]
if dir == "n" then
y = y+1
elseif dir == "ne" then
y = y+1
x = x+1
elseif dir == "e" then
x = x+1
elseif dir == "se" then
y = y-1
x = x+1
elseif dir == "s" then
y = y-1
elseif dir == "sw" then
y = y-1
x = x-1
elseif dir == "w" then
x = x-1
elseif dir == "nw" then
y = y+1
x = x-1
elseif dir == "u" or dir == "up" then
z = z+1
elseif dir == "down" then
z = z-1
end
setRoomCoordinates(roomID,x,y,z)
centerview(roomID)
setRoomEnv
- setRoomEnv(roomID, newEnvID)
- Sets the given room to a new environment ID. You don't have to use any functions to create it - can just set it right away.
- See also: setCustomEnvColor()
- Example
setRoomEnv(551, 34) -- set room with the ID of 551 to the environment ID 34
setRoomIDbyHash
- setRoomIDbyHash(roomID, hash)
- Sets the hash to be associated with the given roomID. See also getRoomIDbyHash().
- If the room was associated with a different hash, or vice versa, that association will be superseded.
setRoomName
- setRoomName(roomID, newName)
- Renames an existing room to a new name.
- Example
setRoomName(534, "That evil room I shouldn't visit again.")
lockRoom(534, true) -- and lock it just to be safe
setRoomUserData
- setRoomUserData(roomID, key (as a string), value (as a string))
- Stores information about a room under a given key. Similar to Lua's key-value tables, except only strings may be used here. One advantage of using userdata is that it's stored within the map file itself - so sharing the map with someone else will pass on the user data. You can have as many keys as you'd like.
- Returns true if successfully set.
- See also: clearRoomUserData(), clearRoomUserDataItem(), getAllRoomUserData(), getRoomUserData(), searchRoomUserData()
- Example
-- can use it to store room descriptions...
setRoomUserData(341, "description", "This is a plain-looking room.")
-- or whenever it's outdoors or not...
setRoomUserData(341, "outdoors", "true")
-- how how many times we visited that room
local visited = getRoomUserData(341, "visitcount")
visited = (tonumber(visited) or 0) + 1
setRoomUserData(341, "visitcount", tostring(visited))
-- can even store tables in it, using the built-in yajl.to_string function
setRoomUserData(341, "some table", yajl.to_string({name = "bub", age = 23}))
display("The denizens name is: "..yajl.to_value(getRoomUserData(341, "some table")).name)
setRoomWeight
- setRoomWeight(roomID, weight)
- Sets a weight to the given roomID. By default, all rooms have a weight of 1 - the higher the weight is, the more likely the room is to be avoided for pathfinding. For example, if travelling across water rooms takes more time than land ones - then you'd want to assign a weight to all water rooms, so they'd be avoided if there are possible land pathways.
Note: The minimum allowed room weight is 1.
- To completely avoid a room, make use of lockRoom().
- See also: getRoomWeight()
- Example
setRoomWeight(1532, 3) -- avoid using this room if possible, but don't completely ignore it
speedwalk
- speedwalk(dirString, backwards, delay, show)
- A speedwalking function will work on cardinal+ordinal directions (n, ne, e, etc.) as well as u (for up), d (for down), in and out. It can be called to execute all directions directly after each other, without delay, or with a custom delay, depending on how fast your game allows you to walk. It can also be called with a switch to make the function reverse the whole path and lead you backwards.
- Call the function by doing:
speedwalk("YourDirectionsString", true/false, delaytime, true/false)
- The delaytime parameter will set a delay between each move (set it to 0.5 if you want the script to move every half second, for instance). It is optional: If you don't indicate it, the script will send all direction commands right after each other. (If you want to indicate a delay, you -have- to explicitly indicate true or false for the reverse flag.)
- The show parameter will determine if the commands sent by this function are shown or hidden. It is optional: If you don't give a value, the script will show all commands sent. (If you want to use this option, you -have- to explicitly indicate true or false for the reverse flag, as well as either some number for the delay or nil if you do not want a delay.)
- The "YourDirectionsString" contains your list of directions and steps (e.g.: "2n, 3w, u, 5ne"). Numbers indicate the number of steps you want it to walk in the direction specified after it. The directions must be separated by anything other than a letter that can appear in a direction itself. (I.e. you can separate with a comma, spaces, the letter x, etc. and any such combinations, but you cannot separate by the letter "e", or write two directions right next to each other with nothing in-between, such as "wn". If you write a number before every direction, you don't need any further separator. E.g. it's perfectly acceptable to write "3w1ne2e".) The function is not case-sensitive.
- If your game only has cardinal directions (n,e,s,w and possibly u,d) and you wish to be able to write directions right next to each other like "enu2s3wdu", you'll have to change the pattern slightly. Likewise, if your game has any other directions than n, ne, e, se, s, sw, w, nw, u, d, in, out, the function must be adapted to that.
- Example
speedwalk("16d1se1u")
-- Will walk 16 times down, once southeast, once up. All in immediate succession.
speedwalk("2ne,3e,2n,e")
-- Will walk twice northeast, thrice east, twice north, once east. All in immediate succession.
speedwalk("IN N 3W 2U W", false, 0.5)
-- Will walk in, north, thrice west, twice up, west, with half a second delay between every move.
speedwalk("5sw - 3s - 2n - w", true)
-- Will walk backwards: east, twice south, thrice north, five times northeast. All in immediate succession.
speedwalk("3w, 2ne, w, u", true, 1.25)
-- Will walk backwards: down, east, twice southwest, thrice east, with 1.25 seconds delay between every move.
Note: The probably most logical usage of this would be to put it in an alias. For example, have the pattern ^/(.+)$ execute:
speedwalk(matches[2], false, 0.7)
And have ^//(.+)$ execute: speedwalk(matches[2], true, 0.7)
Or make aliases like: ^banktohome$ to execute speedwalk("2ne,e,ne,e,3u,in", true, 0.5)
Note: The show parameter for this function is available in Mudlet 3.12+
stopSpeedwalk
- stopSpeedwalk()
- Stops a speedwalk started using speedwalk()
- See also: pauseSpeedwalk(), resumeSpeedwalk(), speedwalk()

local ok, err = stopSpeedwalk