Manual_Technical Manual - Mudlet
Manual_Technical Manual - Mudlet
Manual:Technical Manual
Note: Would you like a section-by-section view of the manual instead? See here.
Command Line
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.
Command-line Shortcuts
SHIFT+Left Highlight one character left of the cursor (or unhighlight if already highlighted).
SHIFT+Right Highlight one character right of the cursor (or unhighlight if already highlighted).
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 1/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
This will inform you about the file name and path of the log file. If you want to log in color you can choose 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. This, along with other options, can be set in the Preferences window (Alt+P).
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 on the
command line:
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
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+).
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 (https://forums.mudlet.org/viewt
opic.php?f=6&t=23023). On Mudlet 4.10 and earlier, a pre-installed send-to-all-profiles package provided control through the :<command> alias.
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:
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
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 2/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
d = 1
Note: You can't use a + b to concatenate string values. For this you must use the double-dot: ..
a = "Jim"
b = "Tom"
c = 350
d = 1
function simple_addition(a,b)
return a+b
end
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:
-- 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
Tables as Lists
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:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 3/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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.
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:
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:
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,
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.
Head to the variables view in the Mudlet editor and tick the box besides a variable - Mudlet will remember it between restarts now!
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.
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 (http://lua-users.org/wiki/TablesTutorial) 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().
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 4/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
mychar = {
name = "Bob",
age = 26,
sex = "male"
}
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.
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 5/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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.
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:
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 )
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:
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:
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?".
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 6/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
end
end
Alias Examples
Alias:
^cc( .+)?
Script:
Shift+Left Arrow Moves and selects text one character to the left.
Considerations
Mudlet 4.17.2 currently does not support named capture groups for aliases.
You will need to use matches[1],matches[2] etc. instead.
You can use modifiers (https://perldoc.perl.org/perlre#Modifiers) for these regexes. Declare these at the start, in the form (?modifiers)
For example, to match the command test, ignoring case, you would need to declare the regex as being case-insensitive, like so: (?i)^test$
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 7/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Note: QUICKSTART: Here is a simple video tutorial (http://www.youtube.com/watch?v=URbwW41LBcQ&hd=1) on how to make basic
triggers in Mudlet.
There are three ways to save your changes; click on the save icon, adding another new trigger, clicking on another trigger item. Triggers that have not
been saved yet cannot be activated.
Note: If you see a bug icon instead of an activation box, there is some error that prevents activation of 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 choose "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.
This is one of the most used form of triggers in mudding. 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()
Testing Triggers
You can test your triggers with the `echo alias from the command line. This requires the echo package, which is installed by default on a new profile.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 8/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
`echo A test line.
feedTriggers([[
You are carrying:
a credstick a pair of steel toed boots (worn)
a Soko Sukeban (worn) a medikit
a cherry moon katana a GPS device
a NV contacts a Tsunami MkII
a MeshGirl Helm an Alto 500 CellPhone
a Kantan Sukeban (worn)
Your load barely slows you down.
]])
Alternatively, you can also record a replay and play it - triggers will be matched on it.
Substring
This trigger type will match any text on a single line. Useful for matching strings of text which don't change at all.
Examples:
Pattern: pond
String: The frog swims in the pond.
Outcome: match (pond matches the word pond)
Pattern: pond
String: The frog swims in the swamp.
Outcome: no match (pond does not match swamp)
Perl Regex
This trigger type will match text using Regular Expressions (Regex). Regex in Perl is a special text string for describing a search pattern within a given
text. For example \w+ is used to match a single word, or \d is used to match a single digit.
Pattern matching also allows the match to be saved in the matches table variable if enclosed in parentheses. matches[1] contains the entire line of the
trigger whereas matches[2] contains the first regex pattern (in our examples pond or swamp).
Examples:
Note: regex101.com (http://regex101.com) is highly recommended to testing out your regular expressions. It includes a pattern tester, cheat sheet
and explanations about the matches.
Start of Line
This is a combined variation of substring matching and regex matching. This type will match any line with text at the start of the string only.
Examples:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 9/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Note: This is exactly the same as using a Perl regex pattern with the ^ anchor (start of a line).
Exact Match
The string must match exactly the pattern. On a whole line, this is the same as using a perl regex pattern with the ^ and $ (start and end of line) anchors.
Examples:
Lua Function
The purpose of Lua function triggers is to be able to run Lua scripts as trigger conditions. This trigger types takes an actual Lua function as the pattern.
This function must return true or false to evaluate correctly, but will only match when returned true.
For example, let's say we wish to enable our entire offensive combat triggers when we commence combat, but otherwise be disabled when we are not in
combat. One would create a trigger chain that contains all the offensive triggers. The chain head (the root trigger of the chain) simply contains this Lua
function condition as its only trigger condition: return inCombat
Now, whenever you enter combat you set the variable "inCombat" to true and thus automatically enable you entire combat triggers that are otherwise
disabled.
Examples of patterns:
Another example:
Create a new trigger with the pattern checkHealth(). Define a new Lua function checkHealth(). Open the script editor, add a new script "health
monitor" and add this code to the new script.
function checkHealth()
if health <= 100 then -- health is a variable we capture from e.g. the prompt or GMCP
echo( "WARNING: Low health! I have to run away!\n" )
send( "flee" ) -- we send a command to run away to the game
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 Lua Function Conditions (LFC) making use of and true or false at the end, that'd be why.
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]
(http://hisham.hm/2011/05/04/luas-and-or-as-a-ternary-operator/)
Lua Function Conditions (LFC) 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.
Line Spacer
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. See the multline section below for further explanation.
Color Trigger
This type of trigger matches the color of the text, as opposed to the actual text incoming. Both foreground and background matching is available and you
will be prompted to select the required colors.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 10/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Examples:
Pattern: Foreground color [ANSI 12], Background color [ANSI 15] (blue foreground on a white background)
String: The bird flies in the sky.
Outcome: match (the COLOR matches)
Prompt
This type of trigger will only work with servers that have implemented the telnet suboption GO AHEAD. If you server does not implement GA this will be
shown in the bottom right corner of Mudlet with the characters No GA.
This option has one function, to match your prompt and will fire when it does.
Note: to retrieve wildcards in multi-line or multi-condition triggers, use the multimatches[line][match] table instead of matches[].
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 11/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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:
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:
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:
1. 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.
2. 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.
3. Perl regular expression → the condition is true if the Perl regex pattern is matched. You’ll find more information on Perl regex below.
4. 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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 12/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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.
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 13/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
All of the patterns have to match for it to fire. This is a common example of a "shielded regex" - don't run the
expensive regex all the time unless you really need to, and match on the faster begin of line the majority of the
time
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.
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
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 14/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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.
-- 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 (htt
ps://forums.mudlet.org/viewtopic.php?f=6&t=23040).
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.
Example:
Let's assume we want to capture name and class of character, but MUD outputs it two ways.
Instead of creating two different triggers we can create only one containing alternative matching patterns:
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.
Note: To verify whether named groups are available you can use flag mudlet.supports.namedGroups.
Script Editor
The Script editor screen (default key: Alt+E) provides access to Mudlet's automation features such as; triggers, aliases, scripts, timers, keybindings,
variables and buttons. It also has an error console, statistics generator and debug console.
Editor shortcuts
Navigation shortcuts
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 15/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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 (https://www.w3.org/International/questions/qa-
what-is-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 (https://en.wikipedia.org/wiki/Grapheme)).
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 16/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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!
Timer Engine
Mudlet supports four different sorts of timers:
The first can be configured by clicking and will start some code in regular intervals. The others can be used in other scripts you code. All of them are
described in more detail below.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 17/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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
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:
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:
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:
Time remaining
You can use remainingTime() to check how much time remains on a provided Timer.
Using variables
To embed a value of a variable in tempTimer code, you might try using this given what you've learnt:
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:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 18/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
-- 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 (http://www.lua.org/pil/6.1.html) with tempTimer - using a slightly different syntax that has advantages.
For example, you have access variables in its scope, when it goes off:
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:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 19/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Enable/disable triggers
This'll make use of tempTimer to enable a trigger and disable it after a short period of time:
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 (https://discord.gg/kuYvMQ9)!
Stopwatches
The stopwatch feature can be used to time how long things take, e.g. long running functions or how long a fight lasts. Stopwatches can be started,
stopped and reset just like a regular physical stopwatch. They can also be given a name and made to be persistent, meaning that they can keep running
(or timing) when Mudlet has been closed. This gives you the ability to time real-life events. Of course, you can also query how much time has passed and
delete a stopwatch no longer required.
fightStopWatch = fightStopWatch or createStopWatch() -- create, or re-use a stopwatch, and store the watch variable ID in a global variable to access it from anywhere
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 20/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
The watch will now be running. Alternatively, you can create and instantly start a stopwatch in one line;
You can stop a stopwatch and retrieve its run time as follows;
resetStopWatch(fightStopWatch)
Note that resetting a stopwatch does not stop or start it, it's simply resets the time value to zero.
Deleting a Stopwatch
deleteStopWatch(fightTime)
The time can be retrieved at any point of a started and currently running or stopped stopwatch.
getStopWatchTime - returns the time as a decimal number of seconds with up to three decimal places to give a milli-seconds
getStopWatches - returns a table of the details for each stopwatch in existence
getStopWatchBrokenDownTime - returns a table of times for a given stopwatch; days, hours, minutes, etc...
All variable names can be replaced with a string name. Let's rewrite the above code with named stopwatches instead.
fightStopWatch = fightStopWatch or createStopWatch("Fight Stopwatch", true) -- using the name 'Fight Stopwatch' and starting it automatically
stopStopWatch("Fight Stopwatch")
echo("The fight lasted for " .. getStopWatchTime("Fight Stopwatch") .. " seconds.")
resetStopWatch("Fight Stopwatch")
Using Persistence
It is preferable (for technical reasons) to assign a name to a stopwatch that will persist over Mudlet sessions.
Mapper
Mudlet's mapper is split into two parts for the best compatibility on all games:
1. The display of the map itself and functions to modify the map in Mudlet, and
2. 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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 21/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Fear not! Pre-made mapping scripts for many games are available from Mudlet forums (https://forums.mudlet.org/search.php?keywords=mapping+scr
ipt&terms=all&author=&sc=1&sf=titleonly&sr=topics&sk=t&sd=d&st=0&ch=400&t=0&submit=Search) - 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.
Generic Mapper Additions may be useful if your MUD display is atypical. Check through the solutions for multi-line exits and how other players have
handled these situations.
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 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:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 22/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Grid mode:
3D mode:
Areas
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 23/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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
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).
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 24/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
(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)
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.
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 (https://forums.mudlet.org/viewtopic.php?f=8&t=2273&view=unread#unread). In short:
1. Zoom out really far away on the area you'd like to move, and select everything (the selection affects all z-levels as well).
2. Right-click, select move to area, and move them to another area. Your selection will still be selected - do not unselect
3. Right-click again, select move to position, and move all of your still selected rooms in the new area so it fits.
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!
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 25/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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 (http://forums.mudlet.org/viewtopic.php?f=6&t=2739) describes how to add a right click menu to your mapper filled with rooms to
speedwalk to.
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.
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)
Possible dockPositions are: left "l", right "r", top "t", bottom "b" and floating "f"
To ease your work, all new profiles in Mudlet come with a Generic mapper package, which tries to draw a map by guessing most of the information from
your game. It knows the most common ways to write an exit, etc. You can find more details by typing "map basics" in Mudlet.
Even if the generic mapper does not 100% grasp your very game details, you could maybe just adjust a few triggers and be done with it. Remember to
stop by and ask for help in forums or chat, if you get stuck anywhere.
Some players have collected a list of Generic Mapper Additions on how to modify the generic mapper to better fit their game already.
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:
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:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 26/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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.
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
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 (https://wiki.mudlet.org/w/Manual:Lua_Functions#setRoomChar) Lua
function, or via the map's context menu.
a name, typically sent via GMCP. You add it to the map with setRoomName (https://wiki.mudlet.org/w/Manual:Lua_Functions#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.
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.
Font options are global. Overriding them for a single room can be be implemented if requested.
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,
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 27/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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:
If you'd like to use a custom pathfinding algorithm instead of the built-in one, you can do that:
function doSpeedWalk()
echo("Room we're coming from: " .. speedWalkFrom .. "\n")
echo("Room you're going to: " .. speedWalkTo .. "\n")
end
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:
I suggest to start from original name_search function in generic_mapper to avoid common problem.
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 28/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 29/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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.
Map Legend
Caption map symbols
Symbol Explanation
a selected room
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 30/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
single open door leading east, no door in other direction (unlikely in practice unless a one-way exit)
two way door, closed in easterly direction and locked going west (orange is closed, red is locked)
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 31/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
up stub exit; no door, door open, door closed, door locked - in this, and the next three, actual exits have a finer mesh fill
down stub exit: no door, door open, door closed, door locked
out stub exit: no door, door open, door closed, door locked
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 32/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
custom room symbols with user selected colours (on both room and symbol)
Screenshots
Just a few example maps from different players and games:
Notes
1. 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 (http://lua-users.org/wiki/TablesTutorial). Nick Gammon has also written a
nice overview on how to deal with Lua tables (http://www.gammon.com.au/forum/bbshowpost.php?bbsubject_id=6036).
Creating Tables
Tables can be created manually, by scripting or by a return value from a function (e.g. getRoomExits())
Accessing Tables
There are a number of different ways to access tables and it depends on how they are created.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 33/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Here are a few examples from the tables created above.
Now you know how to access table elements, addressing and assigning values to them works in the same way as normal variables.
stats["hp"] = 2000
-- or -- stats.hp = 2000
exits[1] = "down"
-- create a new entry in the stats table with the key called gold and assign it the value of 35
stats["gold"] = 35
stats["gold"] = nil
-- the stats table now only contains hp, mana and moves
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].
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 },
... ...
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 34/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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:
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:
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 (https://www.lua.org/pil/20.2.html). Should you need proper regex
however, Mudlet has lrexlib (http://rrthomas.github.io/lrexlib/manual.html) available - which works as a drop-in replacement; replace string. with rex.
- for example string.gsub to rex.gsub. See manual (http://rrthomas.github.io/lrexlib/manual.html) for documentation.
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.
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 (http://rrthomas.githu
b.io/lrexlib/manual.html#new) and that regexes are greedy by default.
Another thing that may surprise some users is that, when escaping, you need to backslashes:
You can also achieve this using long string literal syntax, where you don't need the double escape:
There are a few functions that you need to know: gsub, count, split, find, match.
count
A single dot here has the same meaning it has in POSIX regexes.
You can also precompute the pattern, using the new function:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 35/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
1
split
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:
find
The find function searches for the first match, and returns the offsets where the match starts and ends.
match
The match function works similarly to the find function, but returns the matches instead of the indices:
gsub
The gsub function replaces the pattern in the string, with the value in the third parameter:
This snippet replaces all the "a", "b", "e" or "f" characters with the empty string, so only "c" and "d" remain.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 36/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Because the regex is greedy, the "ab" is a single match, so it gets replaced.
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 (https://www.lua.org/pil/9.1.html) and a tutorial (http://lua-users.org/wiki/CoroutinesTutorial) 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.
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:
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.supports.coroutines 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.
function batch()
for i = 0, 100 do
coroutine.resume(routine, i)
echo(i .. "% complete.\n")
end
end
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 37/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
processed part of a task.. 4% complete.
processed part of a task.. 5% complete.
...
Introspective facilities
Lua brings a helpful debug.getinfo(function) (https://www.lua.org/pil/23.1.html) 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.
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 38/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
-- 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
Note: Mudlet also uses the event system in-game protocols (like GMCP, MSDP and others).
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.
-- 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/raiseGlobalEvent.
-- "profile" - Is the profile name from where the raiseGlobalEvent was 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
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 (https://doc.qt.io/qt-5/qtgamepad-index.html) was not available on Ubuntu 18.04 LTS (https://packages.ubuntu.com/search?keywords=libqt5
gamepad5-dev).
Mudlet-raised events
Mudlet itself also creates events for your scripts to hook on. The following events are generated currently:
AdjustableContainerReposition
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 39/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
registerAnonymousEventHandler("AdjustableContainerReposition", repositioningContainer)
AdjustableContainerRepositionFinish
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 (http://www.aardwolf.com) who originated this protocol. See this (http://forums.mudlet.org/viewtopic.php?f=6&t=1471) 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
-- 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
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.
sysCustomHttpError
Raised whenever a customHTTP() request fails. Arguments are the error message and the URL that the request was sent to and HTTP method.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 40/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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 (http://en.wikipedia.org/wiki/
Keylogger) either.
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.
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).
sysDeleteHttpError
Raised whenever a deleteHTTP() request fails. Arguments are the error message and the URL that the request was sent to.
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, the file size is
passed as the third, and the HTTP response is passed as the fourth.
-- register our function to run on the event that something was downloaded
registerAnonymousEventHandler("sysDownloadDone", downloaded_file)
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 41/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
-- download a list of fake users for a demo
downloadFile(getMudletHomeDir().."/achaea-who-count.html", "https://www.achaea.com/game/who")
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
sysDownloadFileProgress
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()
progressBar:show()
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 42/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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.
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).
sysGetHttpError
Raised whenever a getHTTP() request fails. Arguments are the error message and the URL that the request was sent to.
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.
sysInstallModule
Raised right after a module is installed through the module dialog. 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.
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 43/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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
registerAnonymousEventHandler("sysIrcMessage", onIrcMessage)
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
sysMediaFinished
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 44/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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
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).
sysPostHttpError
Raised whenever a postHTTP() request fails. Arguments are the error message and the URL that the request was sent to.
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.
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).
sysPutHttpError
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 45/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Raised whenever a putHTTP() request fails. Arguments are the error message and the URL that the request was sent to.
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 46/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Event handlers receive the name of the removed package as additional argument.
sysUnzipDone
Event handlers receive the zip file name and the unzip path as additional arguments.
sysUnzipError
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.
Example
This sample code will echo whenever a resize happened with the new dimensions:
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.
Example
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).
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.
Example
This sample code will echo whenever a resize happened with the new dimensions:
ttsPitchChanged
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 47/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
See also: Manual:Text-to-Speech
ttsRateChanged
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.
ttsSpeechPaused
ttsSpeechQueued
ttsSpeechReady
ttsSpeechStarted
ttsVoiceChanged
ttsVolumeChanged
Supported Protocols
Mudlet negotiates and supports the following telnet based protocols:
CHARSET, GMCP, MSP, MSSP, MTTS, MXP, and NEW-ENVIRON are enabled by default. MSDP and MNES may be enabled in the Settings menu. TLS
is enabled from the Connections dialog for supported games.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 48/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
CHARSET (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.
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.
Negotiating the CHARSET telnet option provides game servers the capability to automatically request a preferred character set with Mudlet per RFC
2066 (https://tools.ietf.org/html/rfc2066). 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
The following is an example of an attempted negotiation where the encoding was not available with Mudlet:
Server Mudlet
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)
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 (https://github.com/keneanung/GMCPAdditions) is a useful tool.
Using GMCP
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:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 49/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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.
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 (http://nexus.ironrealms.com/GMCP),
for information about specific 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
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
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.
A good GMCP tutorial that walks you through receiving and sending GMCP data is available here (http://www.mudlet.org/wp-content/uploads/2013/0
2/GMCPtutorial.pdf) - take a read!
MSDP
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 50/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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 (http://tintin.sourceforge.net/protocols/msdp/) for some of the commands and values your server might
support.
Using MSDP
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:
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.
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 (https://mudhalla.net/tintin/protocols/msdp/) 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")
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 (https://www.zuggsoft.com/zmud/msp.htm) and available in PDF here.
MSP in Mudlet
1. 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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 51/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
2. MSP for Lua - Mudlet triggers may capture and invoke the receiveMSP function available through the Lua interpreter of Mudlet to process MSP.
3. 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).
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.
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:
Note: Game admins: This option does require a TELOPT 90 WILL message.
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.
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
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 52/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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
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 (https://www.zuggsoft.com/zmud/msp.htm).
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.
MSSP
Mud Server Status Protocol, or MSSP, provides a way for game crawlers (i.e. MSSP Mud Crawler (https://tintin.sourceforge.io/protocols/mssp/mu
dlist.html)) and game listing sites (search for Listings here (https://www.reddit.com/r/MUD/)) 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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 53/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
To receive MSSP data in Mudlet, these conditions must be met:
1. The Enable MSSP box in the Settings window of Mudlet must be checked (default on).
2. The game must negotiate MSSP with clients like Mudlet at its login screen. Details here (https://tintin.sourceforge.io/protocols/mssp/).
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 = "[email protected]",
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"
}
MTTS
MUD servers frequently seek information about the capabilities of a MUD Client. Despite the availability of various methods, achieving consistency and
reliability in this endeavor has proven challenging. The Mud Terminal Type Standard (MTTS (https://tintin.mudhalla.net/protocols/mtts/)) aims to
alleviate these issues by introducing a transparent and straightforward standard for MUD Clients to communicate their terminal capabilities. This
standard builds upon and formalizes RFC 1091 (https://datatracker.ietf.org/doc/html/rfc1091), which outlines the Telnet Terminal-Type Option.
MTTS in Mudlet
By incorporating the Mud Terminal-Type Standard (MTTS), Mudlet will communicate with interested servers that it possesses the following capabilities:
Support for ANSI Color Codes: The client supports all common ANSI color codes.
UTF-8 Character Encoding: The client utilizes UTF-8 character encoding.
Support for 256 Color Codes: Mudlet is equipped to handle all 256 color codes.
OSC Color Palette: Mudlet acknowledges support for the OSC color palette.
Screen Reader Support: Mudlet offers support for screen readers, with opt-in functionality (not advertised by default).
Truecolor Codes: Mudlet supports truecolor codes using semicolon notation.
Mud New Environment Standard (MNES) Support: The client adheres to the Mud New Environment Standard for information exchange.
TLS Encryption: The client supports Transport Layer Security for data encryption.
Users can find on the Accessibility tab under the Settings menu a checkbox identified as "Advertise screen reader use via protocols supporting this
notice" which when checked will notify interested game servers. This information may be used to optimize the gaming experience.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 54/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Through a Telnet TERMINAL-TYPE Option negotiation, Mudlet transfers a bitvector to game servers, (i.e., 2349) for processing. A bitvector, also known
as a bitmap, is a data structure that represents a fixed-size sequence of binary digits or bits. In a bitvector, each bit corresponds to a specific position or
index in the sequence, and its value can be either 0 or 1. The MTTS bitvector represents is a set of flags and boolean values, where each bit can represent
the state of a particular boolean condition or flag. For example, if the third bit is set to 1, it indicates that the client is using UTF-8 character encoding. A
0 indicator would indicate that UTF-8 was not supported.
MTTS Bitvector
Bit Property Meaning
128 PROXY Client is a proxy allowing different users to connect from the same IP address.
256 TRUECOLOR Client supports truecolor codes using semicolon notation.
512 MNES Client supports the Mud New Environment Standard for information exchange.
1024 MSLP Client supports the Mud Server Link Protocol for clickable link handling.
2048 TLS Client supports Transport Layer Security for data encryption.
Negotiating MTTS
Per the MTTS guidance, game servers should initiate up to 4 TTYPE requests to complete the TTYPE cycling routine within a given connection. If the
connection is reset, negotiate TTYPE again. Reference the MTTS website (https://tintin.mudhalla.net/protocols/mtts/) for more information.
Server Mudlet
IAC DO TTYPE (24) IAC SE IAC WILL TTYPE (24) IAC SE
IAC SB TTYPE (24) SEND (1) IAC SE IAC SB TTYPE (24) IS (0) MUDLET IAC SE
IAC SB TTYPE (24) SEND (1) IAC SE IAC SB TTYPE (24) IS (0) ANSI-TRUECOLOR IAC SE
IAC SB TTYPE (24) SEND (1) IAC SE IAC SB TTYPE (24) IS (0) MTTS 2349 IAC SE
IAC SB TTYPE (24) SEND (1) IAC SE IAC SB TTYPE (24) IS (0) MTTS 2349 IAC SE
If a Mudlet user does not want to enable Mud Terminal Type Standard, they may choose the Settings, General menu item in Mudlet and toggle off the
"Enable MTTS" checkbox.
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 55/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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")
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.
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. MXP example in Mudlet
<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 (https://www.zuggsoft.c
om/zmud/mxp.htm) or the PDF here. Mudlet has a partial implementation version 1.0 of the MXP spec - to see what is supported, ask Mudlet with the
<SUPPORT> (https://www.zuggsoft.com/zmud/mxp.htm#Version%20Control) tag.
NEW-ENVIRON
To enhance the player experience through sharing more client-supported details, the Telnet New-Environ Option may be used to transfer client
environment variables from Mudlet to game servers. Sharing supporting information on information such as encoding, terminal emulation, and
accessibility options aims to improve initial player setup and increase the retention rate for new gaming community members.
NEW-ENVIRON in Mudlet
Mudlet supports two methods of information exchange via NEW-ENVIRON, the first via RFC 1572 (https://datatracker.ietf.org/doc/html/rfc1572):
Telnet New-Environ Option (on by default), and the second is MNES (https://tintin.mudhalla.net/protocols/mnes/): Mud New-Environ
Standard (off by default), which shares a standardized set of client information across multiple clients.
Mudlet provides a user-friendly interface for managing environmental variables through its Settings menu. For certain environmental variables, manual
selections made in the Settings menus can dynamically notify servers that have expressed interest in the client's environmental variables through the
negotiation of the NEW-ENVIRON option. For instance, when a Mudlet user updates the data encoding for a server profile by navigating to Settings,
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 56/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
General, and choosing a specific data encoding from the drop-down menu, this information becomes available for transmission via both the RFC
(default) and MNES (requires user enabling) options.
Users can find on the Accessibility tab under the Settings menu a checkbox identified as "Advertise screen reader use via protocols supporting this
notice" which when checked will notify interested game servers. This information may be used to optimize the gaming experience.
Two types of variables are used per RFC 152, well-known variables defined with VAR (0) and for less common variables, USERVAR (3). Currently, per
the RFC, Mudlet shares its variables via the USERVAR (3) type.
Some client variables updates may be reported ad-hoc with an INFO (2) message. If there is no value for a defined variable, a VAL (1) will be sent
without a value following it.
OPT-
Type Variable Example Values Mudlet Default INFO Purpose Available
IN
USERVAR CHARSET UTF-8, ASCII Yes Encoding set in the client 4.18
ANSI-TRUECOLOR, ANSI-
ANSI-
USERVAR TERMINAL_TYPE 256COLOR, ANSI, XTERM, Terminal type of the client 4.18
TRUECOLOR
VT100, DUMB
Negotiating NEW-ENVIRON
Negotiating the NEW-ENVIRON Telnet option empowers game servers to request one, multiple, or all client environment variables configured within
Mudlet. The process unfolds with the game server sending a Telopt DO NEW-ENVIRON (39), prompting Mudlet to respond with a WILL NEW-
ENVIRON (39). Subsequently, the game server can send SB NEW-ENVIRON (39) SEND to receive all available environment variables. Mudlet responds
with SB NEW-ENVIRON (39) IS (0) < VAR (0) | USERVAR (3) > "<variable>" [VAL (1)] ["<value>"] [ .. [ VAR (0) | USERVAR (3) ] "<variable>" VAL
(1) "<value>"] containing the list of environmental variables.
Once an environmental variable is transmitted to a server within the ongoing connection, Mudlet replies with SB NEW-ENVIRON (39) INFO (2) < VAR
(0) | USERVAR (3) > "<variable>" [VAL (1)] ["<value>"] messages for select variables. Importantly, no reply from the server is required in this context.
If there is a need to specify a particular list of requested environmental variables to Mudlet, the format SB NEW-ENVIRON (39) SEND < VAR (0) |
USERVAR (3) > "<variable>" [ .. < VAR (0) | USERVAR (3) > "<variable>" ] can be employed.
Server Mudlet
IAC SB NEW-ENVIRON (39) SEND (1) USERVAR (3) CHARSET IAC SE IAC SB NEW-ENVIRON (39) IS (0) USERVAR (3) CHARSET VAL (1) UTF-8 IAC SE
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 57/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Server Mudlet
IAC DO NEW-
ENVIRON (39) IAC WILL NEW-ENVIRON (39) IAC SE
IAC SE
IAC SB NEW-ENVIRON (39) IS (0) USERVAR (3) 256_COLORS VAL (1) 1 USERVAR (3) ANSI VAL (1) 1 USERVAR (3) CHARSET VAL (1) UTF-8 USERVAR
IAC SB NEW- (3) CLIENT_NAME VAL (1) MUDLET USERVAR (3) CLIENT_VERSION VAL (1) 4/17/2-DEV USERVAR (3) USERVAR (3) MTTS VAL (1) 2349 USERVAR (3)
ENVIRON (39) OSC_COLOR_PALETTE VAL (1) 1 USERVAR (3) SCREEN_READER VAL (1) USERVAR (3) TERMINAL_TYPE VAL (1) ANSI-TRUECOLOR USERVAR (3)
SEND (1) IAC SE TLS VAL (1) 1 USERVAR (3) TRUECOLOR VAL (1) 1 USERVAR (3) UTF-8 VAL (1) 1 USERVAR (3) VT100 VAL (1) 0 USERVAR (3) WORD_WRAP VAL (1)
100 IAC SE
[ As updates occur in the client the following are possible... ]
IAC SB NEW-ENVIRON (39) INFO (2) USERVAR (3) CHARSET VAL (1) UTF-8 IAC SE
IAC SB NEW-ENVIRON (39) INFO (2) USERVAR (3) MTTS VAL (1) 2349 IAC SE
IAC SB NEW-ENVIRON (39) INFO (2) USERVAR (3) SCREEN_READER VAL (1) IAC SE
IAC SB NEW-ENVIRON (39) INFO (2) USERVAR (3) UTF-8 VAL (1) 1 IAC SE
IAC SB NEW-ENVIRON (39) INFO (2) USERVAR (3) WORD_WRAP VAL (1) 100 IAC SE
If a Mudlet user does not want to negotiate environmental variables, they may choose the Settings, Special Options menu item in Mudlet and enable
"Force NEW_ENVIRON negotiation off". The following is an example of an attempted negotiation where "Force NEW-ENVIRON negotiation off" is
enabled.
Server Mudlet
MNES
The Mud New-Environment Standard is an alternative way to share client-supported details between Mudlet to game servers. MNES is a variant of
NEW-ENVIRON, not based on the RFC.
Activating MNES
If your game supports MNES, instruct users to toggle on the `Enable MNES` menu option on the General tab in Mudlet.
MNES leverages VAR (0) to transfer up to five client environment variables. Some client variables updates may be reported ad-hoc with an INFO
message. If there is no value for a defined variable, a VAL (1) will be sent without a value following it.
Negotiating MNES
The primary differences between MNES and the out-of-the-box RFC 152 NEW-ENVIRON implementation is that MNES sends no more than 5 client
environment variables ("IPADDRESS" will not be implemented in Mudlet), it uses a VAR (0) for the SEND (1), IS (0), and INFO (2) messages, and
returns a multiple client variable response in multiple IS (0) messages.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 58/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Server Mudlet
IAC SB NEW-ENVIRON (39) IS (0) VAR (0) CHARSET VAL (1) UTF-8 IAC SE
IAC SB NEW-ENVIRON (39) IS (0) VAR (0) CLIENT_NAME VAL (1) MUDLET IAC SE
IAC SB NEW-ENVIRON (39) IS (0) VAR (0) CLIENT_VERSION VAL (1) 4/17/2-DEV IAC SE
IAC SB NEW-ENVIRON (39) SEND IAC SE
IAC SB NEW-ENVIRON (39) IS (0) VAR (0) MTTS VAL (1) 2349 IAC SE
IAC SB NEW-ENVIRON (39) IS (0) VAR (0) TERMINAL_TYPE VAL (1) ANSI-TRUECOLOR IAC SE
IAC SB NEW-ENVIRON (39) INFO (2) VAR (0) CHARSET VAL (1) ASCII IAC SE
IAC SB NEW-ENVIRON (39) INFO (2) VAR (0) MTTS VAL (1) 2345 IAC SE
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 (https://wiki.mudlet.org/w/Sample_TLS_Configuration) or this (https://blog.oestrich.org/2018/11/
nginx-tls-socket) 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.
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 59/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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)
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:
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.
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 60/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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 (http://www.mudbytes.net/forum/comment/63920/#c63920) 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 (http://forums.mudlet.org/viewforum.php?f=9). Once you're done,
package your work for distribution which you can optionally post in the finished scripts (http://forums.mudlet.org/viewforum.php?f=6) section.
Some Mudlet packages may also be exclusively available on your own game-specific website or forums, so make sure to check out what your game has to
offer as well.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 61/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Our Discord server (https://discordapp.com/invite/kuYvMQ9) also has a Package channel where people can showcase their talents. Join our server, get
assistance and talk all things Mudlet.
via URL
Note: since 4.11+
If you have a web link to a package you can drag and drop that link onto an open profile and the package will get merged into that particular profile only.
If you have a file on your computer you can drag and drop this onto an open profile as above. Alternatively, you can manage your packages via the
Package Manager (Alt+O) from the toolbar. The Package Manager show details about installed packages on your system, and you can install and remove
with the buttons at the bottom. The original download does not need to be kept as Mudlet has a copy of it once installed.
via MPKG
If the package you require is available in the Mudlet Package Repository (https://github.com/Mudlet/mudlet-package-repository) you can use the
command line tool called MPKG to install (and perform various other handy tasks like updates).
If MPKG is not installed on your system, use one of the other methods to install it first, i.e. drag and drop this link (https://mudlet.github.io/mudlet-pac
kage-repository/packages/mpkg.mpackage) onto your profile. That link points to the latest version of the MPKG package.
lua installPackage("https://mudlet.github.io/mudlet-package-repository/packages/mpkg.mpackage")
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 62/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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.
Installing Modules
Package Development
Have you made an awesome set of triggers or scripts for your game? Wish to share it with your fellow players and Mudlet users? Read on for information
on how to create a package and get it distributed.
Exported settings are saved into an mpackage that can be imported using any of the supported installation methods (see Installing a Mudlet Package).
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 63/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Each package requires some metadata to explain what the package is all about. Choose a name (or if updating a package, select it from the dropdown list
and it will populate the dialog). When selecting a name, try to ensure if is unique if possible. This helps players differentiate between two packages.
Select the various triggers and scripts you wish to add to the package.
Now add further detail by pressing the Describe your package button to define additional metadata and provide information to Mudlet users that
choose to import your package.
author information,
an icon, 512x512 recommended,
a short description; a one-liner for describing your package
a description highlighting features, command usage and perhaps a screenshot,
a version number.
This information is essential if you wish to be included in the Mudlet Package Repository (https://github.com/Mudlet/mudlet-package-repository).
You can use Github-flavoured markdown (https://guides.github.com/features/mastering-markdown/) in the package description to give a nice
presentation for the player. Try following the guidelines as mentioned in the pre-populated text.
If your package requires other Mudlet packages, add them under the Required packages dropdown. For example you might be creating a set of custom
triggers for a game to use with generic_mapper, this would be considered a dependency otherwise your triggers won't work if another player does not
have generic_mapper installed.
Note: To remove a dependency that has already been selected and added, use CTRL+Delete (Linux/Windows) or FN+Backspace (MacOS).
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 64/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Packages that reference local files such as images, sounds, fonts (.otf, .ttf) since Mudlet 3.0, will need to be declared in the final Assets section. Without
these files the package may work locally but not on another players computer. These files will be copied into
getMudletHomeDir().."/"..packagename upon installation, so your scripts can use them.
For example, if your package is called "sipper" and you have health.png that has 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
{note} To remove an included asset, select it from the list and use backspace (fn + delete on macOS) to remove it.
Click Export to write the mpackage, which will be saved to your desktop by default. Use Select export location to pick a different destination.
mpkg is the command line package manager for Mudlet which allows you to install, remove, update and search for packages in this repository. mpkg links
in to the Mudlet Package Repository (https://github.com/Mudlet/mudlet-package-repository) which provides users with a central location to find
packages they would like to install without having to leave the Mudlet interface.
Submitting A Package
Mudlet Package Repository (https://github.com/Mudlet/mudlet-package-repository) is served via Github. Please check the repository (https://github.c
om/Mudlet/mudlet-package-repository) for instructions on how to get your package uploaded.
If your game currently serves up the a package via GMCP but you would prefer the package was hosted on the Mudlet Package Repository you will need a
hook package to send via GMCP instead to tell Mudlet where to find your game package on the repository.
e.g.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 65/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
If you still wish to self-host your package served up via GMCP, but want to be listed in the Mudlet Package Repository (for game visibility or other
reasons) then you will need an installer package. This would be as simple as creating a package with the Package Exporter and utilizing the API such
that the package would simply install your self-hosted package;
The cons of this method means that any updates to your package and notifying your users is up to you, as it will not be shared with the repository's
update system.
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 (https://github.com/tspivey/mudlet-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.
Alt menus
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
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 66/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
F6
Once a hotkey has been selected, it will allow you to review text using the following shortcuts -
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.
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
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.
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.
Trigger navigation
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.
Accessibility On Windows
Accessibility on OSX
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 67/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Accessibility on Linux
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 (https://wiki.stickmu
d.com/wiki/Screenreader).
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.
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.
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 (https://github.com/ironcross32/QuickOutput-for-Mudlet)
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 (https://github.com/ironcross32/ChannelHistory).
a = "Tom"
matches[2] = "Betty"
b = matches[2]
c = a .. b and e will equal "TomBetty"
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 68/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
To output a table you can use a convenience function - display(mytable), which is built into Mudlet.
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:
number_of_weapons = matches[2]
status_of_weapons = matches[3]
notice = number_of_weapons .. status_of_weapons
echo( notice )
send( "put weapons in backpack" )
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).
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:
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.
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.
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:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 69/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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.
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.
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( "" )
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 70/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Then the output will be changed to: "Mary and walk to the diner."
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()
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.
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:
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.
Dynamic Triggers
triggerID = tempTrigger( substring pattern, code ) creates a fast substring matching trigger
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 71/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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])
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().
cecho("sys", string.format([[
/---------\
%s
%dyrs
sex - %s
\---------/
]], name, age, sex))
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!
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 72/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
sleeping = false
end
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+))?$
Trigger: ^ (regex)
Code:
miniconsoleContainer =
miniconsoleContainer or Adjustable.Container:new({name = "miniconsoleContainer"})
myMiniconsole =
Geyser.MiniConsole:new(
{
name = "myMiniconsole",
x = 0,
y = 0,
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 73/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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")
-- 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:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 74/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
tempTimer(0, [[mycode]])
moveCursor(0,getLineCount()-1)
deleteLine()
moveCursor(0,getLineCount())
deleteLine()
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:
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:
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.
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:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 75/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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:
It tests if city == "Magnagora" OR city == "New Celest", but with a more concise syntax for longer lists of items.
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:
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:
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'
}
}
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:
This will return all your friends in Magnagora, sorted by their name, from smallest to largest. To reverse this, you would simply do:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 76/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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:
This will return every friend you have, sorted first by city and then their name.
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:
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 77/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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"
}
})
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:
-- 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.
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:
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 78/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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:
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:
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:
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.
Discord Messages
Can you send messages from Mudlet to Discord? Totally. Here is an example:
function sendToDiscord(data)
local url = "https://discord.com/api/webhooks/1204151397977821184/Cu8ZQQo9R11AyIt3DxpOEeB8MtVMA6_AEfXoZaYxqEAOu_6hwhtA2cRLIw-VIs7py7p8"
local headers = {["Content-Type"] = "application/json"}
local json = yajl.to_string(data)
postHTTP(json, url, headers)
end
local data = {
content = "Hello, Discord!",
embeds = {
{
title = "This is an embed",
url = "https://example.com",
image = {
url = "https://example.com/image.jpg"
}
}
}
}
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 79/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
sendToDiscord(data)
Sure enough, after starting this script, you can see a message in Discord:
What you just need to do is create a webhook in a channel. Go to channel settings, then create this:
Here you can find more documentation on which fields Discord allows: https://discord.com/developers/docs/resources/webhook#execute-webhook
All this is one way though. Mudlet won't listen to messages from Discord. For that you'd probably have to make a Discord bot first.
To respect the players privacy, this option is disabled by default - enable it by ticking the Discord
option for the profile:
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 (https://www.mudlet.org/contact/) to let us know your game implements GMCP.
GMCP
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 80/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
5. 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 (https://discordapp.com/developers/docs/rich-presence/best-practices#tips) for filling it in.
6. 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 (https://discordapp.com/developers/applications/me) and set it with setDiscordApplicationID(), then set the set the rest of the options as
necessary:
Credit: Discord
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.
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:
To process Client.Media GMCP data in Mudlet, these boxes in the Settings window of Mudlet must be checked:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 81/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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:
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.
Yes "url" <url> Resource location where the media file may be downloaded.
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.
Maybe "url" <url> Resource location where the media file may be downloaded.
Only required if a url was not set above with Client.Media.Default.
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
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 82/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Required Key Value Default Purpose
"sound" or
No "type" "sound" Identifies the type of media.
"music"
Volume increases, or fades in, ranged across a linear pattern from one to the volume set with the "volume" key.
No "fadein" <msec> Start position: Start of media.
End position: Start of media plus the number of milliseconds (msec) specified.
1000 milliseconds = 1 second.
Volume decreases, or fades out, ranged across a linear pattern from the volume set with the "volume" key to one.
No "fadeout" <msec> Start position: End of the media minus the number of milliseconds (msec) specified.
End position: End of the media.
1000 milliseconds = 1 second.
No "priority" 1 to 100 Halts the play of current or future played media files with a lower priority while this media plays.
No "key" <key> Uniquely identifies media files with a "key" that is bound to their "name" or "url".
Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.
name
For example, to simply play the sound of a cow mooing already stored in the "media" folder:
Client.Media.Play {
"name": "cow.wav"
}
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"
}
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 83/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
The "type" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.
tag
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:
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:
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:
Client.Media.Play {
"name": "the_matrix.mp3",
"type": "music",
"volume": 50,
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 84/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
"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:
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.
finish
Finish playing a media track at the number of milliseconds specified. Example values, followed by syntax examples:
Client.Media.Play {
"name": "mudlet_beatboxing.mp3",
"type": "music",
"volume": 75,
"finish": 35000
}
Although using the integer type is recommended, Mudlet parses "finish" values of type string ("100") into integers (100) as needed.
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 85/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
The "priority" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.
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
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 86/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Required Key Value Purpose
No "name" <file name> Stops playing media by name matching the value specified.
"sound" or
No "type" Stops playing media by type matching the value specified.
"music"
No "tag" <tag> Stops playing media by tag matching the value specified.
No "priority" 1 to 100 Stops playing media with priority less than or equal to the value.
No "key" <key> Stops playing media by key matching the value specified.
Decrease volume from the current position for a given duration, then stops the track.
No "fadeaway" true or false Given duration is the lesser of the remaining track duration or the fadeout specified in Client.Media.Play.
If fadeout was not specified in Client.Media.Play, then the optional fadeout parameter from Client.Media.Stop or a default of 5000
milliseconds will be applied.
No "fadeout" Default duration in milliseconds to decrease volume to the end of the track.
Only used if fadeout was not defined in Client.Media.Play.
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.
Client.Media.Stop {
"name": "rain.wav"
}
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
}
Client.Media.Stop {
"key": "area-music"
}
Decrease volume for 5 seconds (or the fadeout parameter defined in Client.Media.Play) and then stop all playing music files for this profile
Client.Media.Stop {
"fadeaway": true
}
Decrease volume for 10 seconds all media categorized with the "key" of "area-music" and then stop the music
Client.Media.Stop {
"key": "area-music",
"fadeaway": true,
"fadeout": 10000
}
Geyser
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 87/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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.
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 (http://forums.mudlet.org/viewtopic.php?f=6&t=4098).
Simple Window Managers manual, and download, can be found here (http://forums.mudlet.org/viewtopic.php?f=6&t=3529).
Useful Resources
There are several useful resources you can refer to when creating your GUI.
Wiki Resources
Geyser Tutorial:
Excellent for getting an initial feel of how to use the Geyser layout manager.
GUI API:
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 (http://www.godwars2.org)
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().
Note: Developer tip: Make a keybinding for resetting your profile while you develop your GUI so you don't have to type lua resetProfile()
command every time you want to see the changes (e.g. CTRL+SHIFT+R)
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 88/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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
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
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 do local 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.
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.
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.
-- 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 {}
If you wish for parts of your script to not be executed when clicking on a script, you may use a guard variable to only code execute once during some
initialization step.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 89/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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:
-- as
myVariable = something and "x" or "y"
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 (https://forums.mudlet.org/viewtopic.php?f=8&t=1211) with more information.
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
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
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 (https://www.lua.org/pil/16.html) on Object Oriented Programming does a good job of explaining it.
GUI
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
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 90/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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.
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
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
-- 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
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 91/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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 or via the Mudlet Package Repository
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.
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.
matches[n]
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 target
you can access it via matches["target"] or simply matches.target. You can use mudlet.supports.namedGroups flag to
determine whether named groups are supported.
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
multimatches[n][m]
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.
Contains translations of some common texts (right now, exit directions only) that are helpful to you in Lua scripting, as well as the
mudlet.translations
current language selected for the user interface. - See translateTable()
Makes your life easier when creating new keybindings via Lua by translating the key name into the number needed - see
mudlet.key
tempKey().
mudlet.keymodifier Same as mudlet.key, but for keyboard modifiers - Ctrl, Alt, etc.
Lists special functionality that the users Mudlet supports - right now, just mudlet.supports.coroutines & mudlet.supports.namedGroups
mudlet.supports
is listed. Use mudlet.supports to conditionally enable functionality as it's available on the users Mudlet.
Color definitions used by Geyser, cecho, and many other functions - see showColors(). The profile's color preferences are also
color_table
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.
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 92/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
Scripting Object Functions: A collection of arrows that manipulate Mudlets scripting objects - triggers, aliases, and so forth.
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 (https://www.lua.org/manual/5.1/). Mudlet also includes several bundled
modules to assist with various additional tasks, or you can add your own.
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.
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
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.
echo
echo([miniconsoleName or labelName], text)
This function appends text at the end of the current line.
Parameters
Example
-- a miniconsole example
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 93/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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
Parameters
msg:
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
Parameters
msg:
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 94/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
-- 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)
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.
Note: If you want your command to be checked as if it's an alias, use expandAlias() instead - send() will ignore them.
Note: The game server can choose not to show commands sent on screen (for example, if you're typing in a password).
-- to send directions:
speedwalk("s;s;w;w;w;w;w;w;w;")
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 (https://lunarmodules.github.io/luasql/manual.html) 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.
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
Example
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 95/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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 as it will also open and return a reference to the database. 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().
Note: Known bug! This function will accept characters other than a-z, but will convert uppercase characters to lower and strip any others including
numbers. For example "My DB" and "my-db_2024-07-09" would both result in a database simply named "mydb", as you can imagine this can lead to
unexpected behaviour. In order to preserve backward compatibility, there is currently no intention to fix this.
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
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:
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:
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:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 96/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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.
-- 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:
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)
1. one When passed an actual result table that was obtained from db:fetch, it will delete the record for that table.
2. two When passed a number, will delete the record for that _row_id. This example shows getting the row id from a table.
3. three As above, but this example just passes in the row id directly.
4. 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.
5. 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:
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:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 97/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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
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
Then you can use the following code in a separate alias to query your database using the previously retrieved _row_id.
Example
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 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. These references do not contain any actual data, they only point to
parts of the database structure.
Example
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.
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 98/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
First, note the trailing underscore carefully! It is required.
The following example illustrates the use of in_:
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
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:
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:
If you are also now aware of a new arrival in San Francisco, you could add them to that existing table array:
And commit all of these changes back to the database at once with:
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 99/327
3/2/25, 22:34 Manual:Technical Manual - Mudlet
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.
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:
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"
https://wiki.mudlet.org/w/Manual:Technical_Manual#MUD_Client_Media_Protocol 100/327