Manual:Technical Manual

From Mudlet
Jump to: navigation, search

Contents

Multi Session Gaming

Mudlet lets you play several simultaneous MUD sessions. However, currently we have the restriction that you cannot use the same profile twice. Consequently, if you want to play three characters on the same MUD at the same time, you need to make 3 profiles with 3 different names e.g. ernie@avalon.de, bert@avalon.de etc.

Split Screen

Mudlet has a split screen. If you scroll up in the MUD text screen (or any other mini console window), the screen will split in two parts. The lower part will follow the MUD 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 control+return 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 usage is necessary 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.

Command Line Auto-Completion, Tab-Completion and Command History

Mudlets command line is especially designed for MUD and MUSH playing. It aims at reducing the amount of typing by using autocompletion and tab completion schemes that are optimized for typical MUD 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 MUD output buffer for words matching the word that you are currently typing. This is useful if you have to type complicated long names. You only have to type the first letters and then press the tab key until the proposal is what you want.

Autocompletion tries to match your current typing with your command history. Example: If you typed the same command a while ago, you only have to start typing the first couple of letters and then press the cursor up key until the proposal matches the command that you want to use.

Command history - if you haven’t started to type anything yet, you can browse through your command history with the cursor up and cursor down keys. However, if you have started typing pressing cursor up will result in a shot at autocompletion.

Escape key - to get out of autocompletion you can press the ESC key any time. After pressing ESC the entire text gets selected and you can overwrite it or get back into command history mode.

Logging Output to text or HTML Log Files

Press on the little button with the blue folder with the green arrow icon on the lower right side of the command line to turn on plain text logging. Click again to stop logging. This will inform you about the file name and path of the log file. If you want to log in color you can chose to log to files in html format, but note that due to the nature of HTML, these log files tend to get very large quickly.

Log files can be found at the mudlet home directory in your profile directory. To get the path to your mudlet home directory you can run a script like this one:

echo( getMudletHomeDir() .. "\n" )

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

Exporting and Importing Profiles or Packages

Mudlet supports XML packages that can be imported and exported while playing. You can find a package section on the forum, where you can download demo packages or ready made packages for your MUD or upload your own packages to share your work with other players. A package can contain anything ranging from a single trigger to hundreds of button groups, trigger groups aliases - in other words, entire "systems".

Importing Packages

To import a package, open the script editor and click the import icon, select your xml package file and import it. Package files might be compressed to save space. If the file is compressed, you’ll need to uncompress it before importing it. The imported package will be stored permanently in your profile when you safe the profile. If you don’t like the imported package, delete its components manually or simply don’t save the profile. Then the new content will be lost on restart. Good packages will be organized in such a way that they will be easy to update or remove.

Packages are nothing else, but profiles - or parts of profiles that can be exchanged, imported and exported between your own profiles and between different players. From a technical perspective a package and a profile xml file are the same thing.

Exporting Packages

To export a single set of items, you can select them and hit the 'Export' button on top of the script editor.

To export several different types of items, go to Toolbox → Package Exporter. Tick the items you'd like to export, select a file to export to, and hit Export.

To export your entire profile e. g. to make a backup on a flash drive, use the "save profile as" button. You can export packages of a trigger branch, alias branch, function key, scripts etc. by clicking on a folder in the tree of the particular item in question and then click on the export icon. You’ll be asked to give a filename for your package. You can export arbitrarily complex structures by moving them into a folder that e.g. is named after the package you’d like to make.

Sharing your System with others - Making complex Packages

If you have written a nice set of triggers, buttons, scripts etc. or maybe even a fully fledged "system" of some sort and you want to share it with others, you can make nice packages that other people can import with a single mouse click. The recommended procedure to make a large package that contains groups of all sorts of items e.g. trigger groups, individual triggers, scripts, buttons, aliases etc., is to export the entire profile with "save profile as". Then create a new empty profile e.g. with your package name. Don’t give a server or port name in the connection dialog and "connect". Mudlet will load the new empty profile although you are offline. Open the script editor and import your previously exported profile and then delete all items that are not part of the package that you are making. Finally, make a folder (group) that is named after your package name and version number e.g. "Johnny’s curing system 12-3-2009" and move all respective items into this folder and repeat the same procedure for all triggers/aliases/scripts etc.. This will make it much easier for other people to import your package and stay updated if you release a newer version. Then save your profile and use the "save profile as" button to create your package.

Using Variables in Mudlet

One of the major design goals in Mudlet was to integrate scripts and variables into triggers/aliases/buttons etc. as seamlessly as possible. The usage of variables in Mudlet is distinctly different from the other major clients, as native Lua scripting has been integrated into Mudlet from the ground up. As scripts are so closely intertwined with the core of Mudlet, variables do not need any special treatment as in other clients i.e. there is no need for code such as:

totalKills = getVariable("killedMonsters") + getVariable("killedVillains")
echo( "kills=" .. totalKills )

In Mudlet, the above code translates into:

totalKills = killedMonsters + killedVillains
echo( "kills=" .. totalKills )

If you define a variable in any given script in Mudlet, be it a trigger, a button, an alias key, an event handler, a free function, etc. It can be used from within any context without any special getVariable() type of function or any special variable symbols, such as @myVar etc.. In Mudlet all variables are native Lua variables. Each session (= profile/connection tab) runs in its own dedicated Lua interpreter. Consequently, all scripts of a profile are compiled into the same Lua interpreter and thus their code runs in the same variable space. All scripts from another simultaneously opened profile will not interfere because each profile uses its own Lua interpreter. Note Everything shares the same variables & functions.

To give you an example: Let’s make a little trigger that counts how many monsters you have killed. Each time you have made a new kill, the trigger matches on the kill message and runs a little script that increases the amount of kills by one each time the trigger fires - in other words, each time you kill a monster and the kill message is sent from the MUD. For the kill counter we declare a variable and call it myKills. This variable is going to hold the number of kills we’ve made so far. The script will look like this:

myKills = myKills + 1

Then we add a little alias, a button or a keybindings that executes another little script that prints your current kill statistics on the screen. The attached script would look like this:

echo( "I have killed " .. myKills .. " monsters today." )

Lua variables can be either a string or a number. They are whatever there were initially initialized with or what data type they can be converted to.

a = "Jim"
b = "Tom"
c = 350
d = 1
 
--Then you can write:
 
e = c + d and e will equal 351
e = a .. b and e will equal "JimTom" 
e = a .. c and e will equal "Jim350"

Note: You can't use a + b to concatenate string values. For this you must use the double-dot: ..

There is another form of variables in Lua called tables which can be used for lists, arrays or dictionaries. This is explained later. For an in-depth coverage of variables in Lua take a look at a Lua tutorial e. g. this one on numbers http://Lua-users.org/wiki/NumbersTutorial and this one on strings http://Lua-users.org/wiki/StringsTutorial or this one on Lua tables http://Lua-users.org/wiki/TablesTutorial

Let’s get back to our example. The trigger script expects myKills to be a number so you have to initialze the variable myKills to 0 before running the script for the first time. The best place to initialize variables is in script script outside of a function definition as this code is executed when the session is loaded or if you compile the script again after you have edited it. To do this click on the "Scripts" icon and select the standard script "My Global Variable Definitions". If you are using an older version of Mudlet or a profile that doesn’t have this script item, simply click on the "Add" icon and make your own script. You can call it whatever you want to. Add following code to initialize your new variable myKills to a number and set its value to 0:

myKills = 0

Whenever you edit this script, it will be recompiled and the code will be run as it is not part of a function definition. This is the major difference between trigger-scripts, alias-scripts etc. and script-scripts. Script-scripts can contain an unlimited amount of function definitions and also free code i. e. code outside of a function definition - code that is not enclosed by function xyz() …. end. On saving the script the script gets compiled and the free code is run instantly. All other item scripts, i. e. trigger-scripts etc., secretly define a function name for the script and thus the script is not free code, but function code. When a trigger fires Mudlet calls this invisible function name to run the script e.g. trigger738(), button82(), alias8(). This means that if you define variables inside a trigger script the variable will not be defined before the trigger runs for the first time. However, if you define this variable as free code in a script-script the definition becomes available immediately on script save. Now, whenever you add new variables to your variable definition script, the script gets run and your old variables will be reinitialized and reset to 0. This will be no big problem in most cases as you won’t work on your systems while really playing in most cases. To solve this problem you have two options:

First option: Add a script group (a folder) and add a new script item for each variable you define. This way, editing a variable definition will only reset the edited variable and none of the others that are defined in different scripts. This has the added advantage that you have a nice graphical overview of your defined variables. Note Organize your variables

Second option (more advanced): Change the variable initialization to only initialize the variable if it hasn’t been initialized before, thus keeping the values of previously defined variables. The following code initializes the variable myKills (to the number 0) but only if it hasn't been initialized before. This would look like this:

if myKills == nil then    
    myKills = 0
end

In Lua all undefined variables are initialized to the value nil. The value nil is not the same thing as the number 0 or the empty string "". What it means is that a variable that has the value nil has not been declared yet and does not exist. If a variable does not exist, it cannot be used as its value is undefined at this point. Consequently, increasing the value of nil by one is impossible as the variable doesn’t exist yet and will lead to a Lua error. The above script simply checks if the variable myKills has been defined yet and if it hasn’t, it will declare the variable and set its value to 0.

Tables as Lists

Having variables that hold a single value is the most important usage of variables, but very often you’ll like to define variables that hold a list of values e. g. a list of your enemies, a list the items you are currently carrying etc.. To define a variable to be a list you need to declare it to be a Lua table. Let’s declare the variable myEnemies as a list containing the names of your enemies:

myEnemies = {}

You can now add new enemies to this list by calling the Lua function table.insert( listName, item ) e.g.

table.insert( myEnemies, "Tom" )
table.insert( myEnemies, "Jim" )

To print the contents of your enemy list on the screen you can run this script

display( myEnemies )

Now let’s make a little alias that adds a new name to your enemy list when you type "add enemy " followed by the name of the enemy e. g. "add enemy Peter" Open the alias editor by clicking on the alias icon. Click on the "Add" icon to add a new alias. Choose any name you like for your alias e.g. "add new enemy" and then define following pattern for the alias: ^add enemy (.*) Then add this little script in the script editor below:

table.insert( myEnemies, matches[2] )
echo( "Added a new enemy:" .. matches[2] .. "\n" )

Save the alias and try. Alias are explained in detail below. Another way to declare a list is to define its values directly.

myEnemies = { "Peter", "Jim", "Carl", "John" }

To remove an item from the list you can use the function table.remove( listName, item index ).

Saving variables

You might notice that Mudlet doesn't save your variables between profiles restarts. The reasons for this are technical, but all it means is that you have flexibility in how to deal with them. There are several ways, so the most common and easiest ones will be explained here.

Saving via explicit assignments in scripts

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 compiled & run when the profile is started, these variables will be created and assigned to those values. This was simple to do, but it has one problem - if you want to change the value of the variables to be saved, you have to edit the script by hand each time; and if you change the value of variables while playing via scripting, the new values won't be recorded.

Saving via table.save & table.load

Next, enter a more proper solution. This'll actually save the variables to a file and load them from it - so if you change the variable values, the current ones will be saved, and will be loaded next time properly. This method works with a table containing your variables though, not individual variables themselves - see Lua tables tutorial on how to create and use those.

table.save(where to save, what table to save) takes the location of a file to save variables to, and a table containing your variables to save. Location can be anywhere on your computer, but a good default place is your profile folder, whose location can be obtained with getMudletHomeDir().

mychar = {
  name = "Bob",
  age = 26,
  sex = "male"
}
 
table.save(getMudletHomeDir() .. "/mychar", mychar)
-- sample echo to show where the file went:
echo(string.format("Variables saved in: '%s'", getMudletHomeDir() .. "mychar"))

table.load(where to load from, what table to use) is similar - it takes the location of the file to load, and a table name to use for the loaded variables.

mychar = mychar or {}
table.load(getMudletHomeDir() .. "/mychar", mychar)
display(mychar)
echo("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.

Input Triggers - Mudlets Alias Engine

Note Note: A screencast is available on getting started with aliases - watch it!

Alias are triggers that operate on user input. Mudlet uses hierarchically ordered powerful Perl regex expression alias. We have explicitly chosen not to offer multi condition alias, alias chains or the same trigger types the trigger engine offers because this would be way over the top and is simply not needed for alias expansion - although it should be noted that the processes are closely related, except that aliases, i.e. input triggers, operate on a different data stream, namely the user input stream, whereas triggers operate on the MUD output data stream. The only real difference between output triggers and input triggers is that input triggers can change the input stream they work on, whereas output triggers cannot change the stream itself - output triggers can change what is printed on the screen as a result of the stream, but they cannot change the stream itself. This is a fundamental difference and a deeper understanding is key to getting to grips with Mudlets alias engine. When you enter a command on the keyboard and press enter or return, the text that you have typed in the command line will be forwarded to the alias unit, i. e. the input trigger unit, in form of the Lua variable command. This variable will be matched against all active alias in the hierarchy unless access to an alias branch is locked by the user or by a script. If an alias matches, it will intercept the user command and the original command will be ignored. Upon a match the clear text command is being send as a command to the MUD in replacement of the original command, if a clear text command has been specified by the user and the attached alias script is being executed. However, the initial command that the user has typed in the command line will not be sent unless you do this as part of your script. Consequently, if you want your alias to send a command to the MUD, you’ll either have to specify a clear text command for simple cases or send commands via the attached alias script e.g. send("kill monster"). You may argue that you feel that it is unnecessary work to be forced to send a command replacement yourself, but this very fact makes our alias system way more powerful because it gives you complete control about what is happening. Why is this so? The initial user command is being held in the Lua variable command. When this value changes within the alias unit processing chain, the initial user input that the aliases work on can be rewritten and changed in the process. Consequently, you can substitute the user input step by step - or alias by alias - without that anything happens as far as sending commands is being concerned unless you explicitly decide to do so.

Alias-diagram.png

The example in the diagram above shows 2 matching aliases, but only one of them sends commands to the MUD - 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 MUD than the amount of text the MUD 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 MUD related scripting and this is why it is explained below.

Let’s get back to alias. We start with a simple example.

We want Mudlet to send "put weapon in bag" whenever we type "pwb". Consequently, the pattern is pwb and as the task is so simple it’s enough to enter "put weapon in bag" in the send field. Then we click on save to save the changes and activate the alias by clicking on the padlock icon. Then we leave the trigger editor and test our new alias. After typing "pwb" and pressing return Mudlet will send the command "put weapon in bag" to the MUD.

Let’s move on to a more complicated example that is needed very often.

We want our script to automatically put the weapon in the correct bag as we have many bags and many weapons. The pattern stays the same. ^pwb The ^ at the beginning of the line means that the command starts with pwd and no other letter in front of this. If we define our pattern more clearly, the pattern will match less often. Without the ^ the alias will match and the alias script will always be run whenever there is the sequence of letters "pwd" in your commands. This may not always be what you want. This is why it’s usually a good idea to make the pattern definition as exact as needed by being less general. The more general the pattern, the more often it will match.

Back to our task: The pattern is ^pwb. Let’s assume that we have defined 2 variables in some other script. The variable "weapon" is the weapon we use and the variable "bag" is the name of the bag. NOTE: In Mudlet global variables can be accessed anywhere from within Mudlet scripts - no matter if they have been defined in a trigger script, in an alias script or in a key or button script. As soon as it’s been defined it somewhere it is usable. To make sure that a variable is local only, i. e. cannot be referenced from other scripts, you have to use the keyword local in front of your variable definition. Back to our alias: Pattern is: ^pwb

Script is:

send( "put " .. weapon .. " in " .. bag )

Depending on the values of our variables Weapon and bag the command "pwd" will be substituted with an appropriate command. To set your weapon and bag variables we use 2 more aliases: Alias to set the weapon: uw (\w)+

Script:

weapon = matches[2];
send( "wield " .. weapon )

To set our bag variable: Pattern:^set bag (.*)

bag = matches[2]

Now let’s go back to our initial problem. We want an alias to put our current weapon into our current bag. But what happens if we are in the middle of a fight and absolutely need to sip a healing potions because we are close to death and cannot take the risk that the bag may be too full to take the weapon? We want to upgrade out little alias to take into account that the bag may be full and chose an empty bag instead. To do this we set up a trigger that detects messages that indicate that the attempt to put the weapon in the bag failed. In this trigger we execute this little bag-is-full-detection-trigger Trigger Pattern: (type substring) Your bag is full.

Script:

bagIsFull = true;

This detection trigger will set the variable bagIsFull to true as soon as it sees the message "Your bag is full.". Then you know that you have to use your spare bag to take the weapon.

Now we have the tools to write an improved version of our little alias script:

if bagIsFull then
    send( "put " .. weapon .. " in " .. spareBag )
else
    send( "put " .. weapon .. " in " .. bag )
end

The next example is one of the most common aliases a tell alias: Pattern:^tj (.*)

Script:

send( "tell Jane " .. matches[2] )

Sadly, Jane is your fiancée and the one thing she is a vegetarian and absolutely hates all words that relate to meat. Luckily, you know enough about aliases by now to make her believe that you’d never ever even think about meat. So you head to your global function script (any script item will do as long as you define your variables outside of your function definitions. See the scripts chapter below for more information. In your script "my global functions" you add a Lua table containing a list of all of all words that a vegetarian might hate. For example:

happyJaneTable = { "meat", "burger", "steak", "hamburger", "chickenburger" }

Now you can upgrade your tell-jane script to automatically search our tell for all words that Jane might not like. In case such a word is found we substitute the entire tell with "How is the weather?".

for key, value in ipairs( happyJaneTable ) do     -- looking at each element of the list
    badWord = happyJaneTable[key]                 -- check out the Lua table chapter below for more info
    begin, end = string.find( command, badWord )  -- begin holds the start position of the word, end* the end-position
    if begin ~= nil then                          -- we have found a bad word
        send( "tell Jane How is the weather?" )
        return
    end
end

Trigger Engine

Unlike alias that define patterns that match on user input, triggers define patterns that match on MUD output. In other words, triggers react to text that has been sent by the MUD, whereas alias react to user commands that have been typed into the command line.

Simple Trigger Matching

Simple-trigger.png


Note Note: QUICKSTART: Here is a simple video tutorial on how to make basic triggers in Mudlet.


To begin with, click on the "Add" button to create a new trigger. Then put the text pattern that you’d like to trigger on into the trigger conditions table on the right side of the screen above the script editor. Afterwards, chose the correct pattern type of your trigger pattern in the drop down list on the right side of the trigger pattern i.e. in the second column of the trigger pattern table. If you define multiple patterns in the same trigger, your trigger will run whenever any one of these patterns matches unless you chose the AND-trigger option, in which case the trigger will only fire if all patterns match within a specified amount of lines from the MUD. For more advanced information on AND and OR trigger see the corresponding AND/OR trigger section below. The next step is to define what should happen when the trigger matches. Usually, this will be done by a Lua script in the Lua editor below the table with the pattern list. In the beginning, you can simply chose the "highlight trigger" option to make your trigger highlight the text that it has triggered on or send a clear text command to the MUD whenever the trigger fires until you have learned enough Lua to more meaningful scripts. Clear text command can be defined in the "send plain text" input box next to the trigger name above the pattern table. Finally, you need to save the new trigger and then activate it with the padlock icon button. By default, new triggers are deactivated and thus will do nothing unless you explicitly activate them. Activated triggers show a green tick in the little blue box on the left side of the trigger name in the trigger tree on the left side of the script editor dialog. There is three ways to save your changes. 1. click on the save icon 2. adding a new trigger 3. clicking on another trigger item. Triggers that have not been saved yet cannot be activated. If you see a bug icon instead of an activation box, there is some error that prevents to activate your trigger. Check the error message above the pattern table.

Example: You want to trigger on the word "pond" in a line such as: "The frog swims in the pond. Plop." All you need to do is add "pond" as a pattern and chose "substring" as a pattern type. Then enter the command you like to send to the MUD 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 MUD any time it sees the word "pond" somewhere in the MUD output.

Simple Highlighter Triggers

Beginners should use Mudlets automated highlight triggers in the beginning to get the hang of the different trigger and pattern types quicker. Click on the "highlight trigger" option and pick a foreground and a background color. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. This helps you spot things at a single glance instead of reading the entire text. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.

More advanced users will often want to do custom highlighting from within scripts. This is how it works: If you want to highlight the word "pond" in the above example you have to add the following little Lua script to the script editor on the lower right side of the Script Editor window:

selectString( "pond", 1 )
fg( "red " )
bg( "blue" )
resetFormat()

"AND" and "OR" Condition Triggers

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!" However, it will not execute on "With a loud plop the frog dived into the water." because "plop" in the line is in lower case letters and your condition specified a "P" in upper case. The simplest form of AND-Triggers in Mudlet are Trigger Chains or Filter Chains, whatever you’d like to call it.

Trigger Chains & Filter Chains

"Chains" and "filters" are different trigger group entities in Mudlet and serve completely different ends.

Chains

A chain is defined in Mudlet by making a trigger group and adding a trigger pattern to the group. A group without a pattern is a simple trigger group that serves no other purposes than adding structure to your trigger system in order to organize your triggers better. Such a normal trigger group will always grant access to its children unless it has been explicitly disabled (= all access to itself or any of its children is locked) either manually or by a script.

A trigger group with a defined trigger pattern, however, will behave like a normal trigger and match if the pattern matches. Such a trigger group is called "chain head". A chain head will only grant access to its children if the trigger pattern has matched and the chain has been enabled. Thus, chains can be looked at as a mechanism to automatically enable and disable triggers or groups of triggers when a certain condition has been met i. e. the trigger pattern of the chain head has been matched. (However, technically this is not correct as disabled child triggers will not be invoked if the chain head matches. In other words, in chains you can still have enabled/disabled elements. The idea of a chain can better be described by necessary and sufficient condition - both of which need to be met before a child trigger is being run.)

Adding child triggers to this group will add elements to the trigger chain. These chain elements will only be activated if the chain head has matched before and thus opened the trigger chain. The chain stays open until the "keep chain open for x lines" value has been reached. The default is 0 which means that the chain only stays open for the current line. When access to the chain has been granted all child triggers will be tested against the content of the current line. Consequently, trigger chains are a means to automatically enable/disable trigger groups without the hassle of enabling and disabling trigger groups manually. This has 2 important advantages: Chains are faster than conventional solutions and chains reduce the complexity of your scripts and greatly reduce the usual system bugs that inevitably go along with enable/disable trigger xy function calls as it’s very difficult and error prone to enable and disable your triggers correctly in large complex trigger systems. This is one of the most powerful features in Mudlet and should be used whenever possible.

Let’s look at a practical example for a trigger chain:

My newbie prompt on Achaea looks like this 500h, 500m ex- when I have balance and 500h, 500m e- when I have lost balance. We are going to develop a prompt detection trigger that raises the event gotPrompt and sets the variables myBalance=true or myBalance=false To begin with, we add a new trigger group and add the Perl regex pattern to detect the prompt:

^(\d+)h, (\d+)m

The pattern reads in plain English: At the beginning of a prompt line there are is a number directly followed by the letter h, a comma, a space and another number followed by the letter h. Whenever this pattern matches the trigger will fire and we’ll know that we have a prompt line. We use the 2 numbers that we captured in our pattern to update our health and mana stats.

Detecting balance is more difficult as balance is indicated by the letters ex- on the same line after the prompt and imbalance is indicated by the letters e-. As we have set a pattern in a trigger group (folder), the folder is turned into a trigger chain head. It will now only let data through to its children when its own pattern is matched. In other words, the child triggers of the trigger chain will only receive data on prompt lines. We are going to take advantage of this by adding two simple substring triggers to detect balance and imbalance. The balance trigger pattern is ex- and the imbalance detector pattern is e-.

In the two balance detection triggers we now write myBalance=false and myBalance=true respectively plus a little echo on the screen that shows our current balance status.

We could now add a call deleteLine() to the prompt detection trigger to erase the prompt from the screen if we don’t want to see it as we have computed all relevant information.

Filters

You can turn a trigger chain head into a filter by checking the "filter" option. This changes the content of what is forwarded as trigger text to the children triggers in the chain. Chains forward the content of the current line as trigger text whereas filters forward the matched pattern instead of the current line. In other words, the text of the current line is filtered according to the pattern of the filter. For example: You want to know the exits in the current room. The simplest solution is a simple filter on You see exits to: (.*) Then you simply add triggers to the filter chain such as north, south, west, east etc. The direction triggers will only be called if the filter head has matched.

Imagine the following scenario: You want to collect some berries. You know that the room contains some berries if the room description contains the words "You are inside a forest. There are some strawberries." or "You are inside a forest. There are some blackberries." and there are always only one kind of berry in the room. You make a new substring trigger for this line, but instead of choosing a regular trigger, you chose to add a new trigger group. Now you add You are inside a forest\. There are some (\w+)\. as an Regular Expression to the expression list of the trigger group. When adding conditions to a trigger group, the trigger group turns from an organizational unit into a filter unit, if the "filter" option is checked. From now on this folder is a filter and will only let its matches pass through. In our case this is exactly what we want, because we don’t want to collect all sorts of berries, but we only want 2 particular kinds, namely, strawberries and blackberries, and we know that these berries can only be trusted if they are picked inside a forest as other areas may contain contaminated berries. Now you add two regular triggers to our berry-in-the-forest filter - one containing the condition: strawberries and the other one blackberries. Then we add the commands to pick the particular kind of berry to both triggers (send field). Now what happens is that as soon as a room description reads "You are inside a forest. There are some strawberries/blackberries." the filter will let the kind of berry pass through to our two berry triggers and they will issue commands to pick berries, if there are such berries. However, in any other situation the words "strawberries" and "blackberries" will NOT trigger a pick - only in the above scenario when the filter parent’s condition is met. This is a very nice way to solve complicated problems with a few easy filter chains. This example is trivial, but using filter chains will rapidly show you how formerly complicated things that could only be solved with very complicated regular expressions can be solved easily now with a couple of filter chains.

Multi-Line Triggers and Multi-Condition Triggers

Multi Condition Triggers are the most advanced feature of Mudlets trigger engine. Like trigger chains or filter chains they are a form of AND-Triggers. All conditions in the list must have matched within the specified margin of lines (delta), in order to trigger the script. Normal triggers fire and run the script as soon as one of the conditions in the regex list is met i.e. if one of the regex/string matches match - or the Lua function condition returns true, the trigger script is run. In multiline triggers, however, each single regex/string/Lua function condition in the list has to have matched within the specified margin of lines at least once to trigger the script. The sequence of the conditions is binding. This means that if the 10th regex on the regex list would be matched on the eleventh line after the match of the first line happened, the trigger will NOT run unless the margin of lines is set to 11. If condition #3 is true but currently #2 is waiting to be true, condition #3 is ignored and must be true again after condition #2 has been true. Conditions can also be Lua Functions or plain Lua code that returns a boolean truth value. You can mix all types of conditions to build complex multi-condition triggers that only fire if all conditions are met. This is a very powerful feature as it reduces the amount of scripting to a minimum or even takes away with the need to script formerly complex processes completely. Multicondition triggers are multi-line triggers, i. e. the conditions can all be met in a single line or many lines after the first condition has been fulfilled. This effectively reduces the amount of complexity as you have all the important conditions placed into a single trigger and all the tedious bookkeeping, variable and condition state accounting is being done by Mudlets trigger engine. The result of this is that the amount of manual condition checking via many different trigger scripts and legions of if condition1 == true then check condition2 can be forgotten about. All you have to do is to define the conditions and the final action that is taken if the trigger fires.

Note Note: to retrieve wildcards in multi-line or multi-condition triggers, use the multimatches[line][match] table instead of matches[].

Trigger-engine-diagram.png






Note 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:

  1. You see a pond
  2. You see a frog.
  3. The frog sits on a stong.

Every single one of these 3 lines will be fed into the trigger engine one after another. If we define an OR-trigger with a condition list consisting of 3 condition patterns:

condition #1 pattern = pond condition #2 pattern = frog condition #3 pattern = stone

Whether or not a condition is found to be true also depends on another property, namely the type of the condition. The condition type can be among others:

  1. substring matching → the condition is true if the condition pattern is a substring of the output line from the MUD. 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 MUD.
  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.

in line #1 we get: pond = true. in line #2 we get frog = true and in line #3 two conditions are true i.e. frog=true and stone = true

Because an OR-trigger fires on the first condition that is true and ignores the rest the trigger will only execute 3 times on these 3 lines although 4 conditions are true.

Note 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 MUD 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 MUD clients. 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.

Lua Code Conditions & Variable Triggers - Expression Triggers

In a Lua Code/Function Condition (LFC) you can run Lua code inside the trigger engine directly, as a trigger pattern. If the trigger pattern returns anything Lua considers true (false in Lua is only nil and the boolean false value, everything else is true), then the pattern will be considered to have matched. The easiest example would be a simple variable trigger: add a new trigger and chose pattern type Lua function. Then define this pattern: if health ⇐ 100 then escape() end. If your health is lower than 100, and your escape function with more logic inside it returns true, the pattern will match. Another formulation of the same would be: checkHealth(). For the last formulation to work you have defined a Lua function checkHealth(). Open the script editor, add a new script "health care" and add this code to the new script-script.

function checkHealth()
    if health <= 100 then
        echo( "WARNING: Low health! I have to run away!\n" )
        startEscape()
        return true
    else
        return false
    end
end

{note} Mudlet used to only allow the boolean true value as the return value to consider the pattern to have been a match. It has since been improved to allow any value Lua would consider true - but if you see any LFCs making use of and true or false at the end, that'd be why.

Lua Syntax Primer: Expressions

if A == B then (...)   ----> if A equals B
if A ~= B then (...)   ----> if A *NOT* equals B
if A <= B then (...)   ----> if A is smaller or equal to B
if A >= B then (...)   ----> if A is greater or equal to B
if A < B then (...)    ----> if A is smaller than B
if A > B then (...)    ----> if A is greater than B

The operators and and or behave differently in Lua than in most other programming languages as they are not guaranteed to return a boolean value.[1]

Lua function conditions effectively means that you run the Lua code they represent on every single line that is received from the MUD, 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.

Timer Engine

Mudlet supports 3 different sorts of timers:

Regular GUI Timers

Regular GUI Timers that fire repeatedly in a certain interval specified by the user. To make one, go to the Timers section (1) in Mudlet, click Add (2), select the time periods you'd like the timer to be going off at - save (3) and activate it (4). The timer will go off after your specified interval and then at regular specified intervals after that, until disabled.

Simple timer.png

You can also enable/disable this timer via scripting with enableTimer() and disableTimer():

enableTimer("Newbie timer") -- enables the timer, so 2s after being enabled, it'll tick - and every 2s after that
 
disableTimer("Newbie timer") -- disables it, so it won't go off anymore

Temporary Timers

Temporary Timers are timers that go off only once and are the most common type of timer used for scripting purposes. You don't work with them from the Timers section - you just code with them only.

For a basic introduction to temporary timers, read up about them here. Here, we'll continue expanding on what you've learnt so far.

One thing to keep in mind when working with tempTimers is that they are unlike #wait statements you might see in other clients. While #waits are typically cumulative, tempTimers aren't - they go off from the same point in time. Thus if you'd like two timers to go off - one after 3s, and another 1s after the first one - you'd set the second timer to go off at 4s. For example:

tempTimer(3, [[ echo("this is timer #1 going off 3s after being made\n") ]])
tempTimer(4, [[ echo("this is timer #2 going off 4s after being made - and 1s after the first one\n") ]])

Note Note: Temporary timers cannot be accessed from the GUI and are not saved in profiles.

Stopping

To stop a temporary timer once you've made it and before before it went off - you use killTimer(). You give killTimer(id) the ID of the timer that you've made - which you get from Mudlet when you make it. Here's an example:

-- get and store the timer ID in the global "greeting_timer_id" variable
greeting_timer_id = tempTimer(2, [[ echo("hello!\n") ]])
 
-- delete the timer - thus nothing will actually happen!
killTimer(greeting_timer_id)

Refreshing

You can also use killTimer() to "refresh" a timer - the following code example will delete the previous timer if one exists and create the new one, thus making sure you don't get multiple copies of it:

if portal_timer then killTimer(portal_timer) end
portal_timer = tempTimer(2, [[ send("enter portal") ]])

Using variables

To embed a value of a variable in tempTimer code, you might try using this given what you've learnt:

tempTimer(1.4, [[ echo("hello, "..matches[2].."!\n") ]])

But that won't work as you'd expect it to - that will try and use the value of matches[2] when the timer goes off - while by then, the variable could have changed! Instead, you take it outside the square [[ ]] brackets - this is correct:

tempTimer(1.4, [[ echo("hello, ]]..matches[2]..[[!\n") ]])

Nesting

If you'd like, you can also nest tempTimers one inside another - though the first [[]]'s will become [=[ ]=]:

tempTimer(1, [=[
  echo("this is timer #1 reporting, 1s after being made!\n")
  tempTimer(1, [[
    echo("this is timer #2 reporting, 1s after the first one and 2s after the start\n")
  ]])
]=])

If you'd like to nest more of them, you'd increase the amount of ='s on the outside:

tempTimer(1, [==[
  echo("this is timer #1 reporting, 1s after being made!\n")
  tempTimer(1, [=[
    echo("this is timer #2 reporting, 1s after the first one and 2s after the start\n")
 
    tempTimer(1, [[
      echo("this is timer #2 reporting, 1s after the second one, 2s after the first one, 3s after the start\n")
    ]])
  ]=])
]==])

Closures

Last but not least, you can also use closures with tempTimer - using a slightly different syntax that has advantages of being able to access variables in it's scope, when it goes off:

local name = matches[2]
tempTimer(2.4, function() echo("hello, "..name.."!\n") end)

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 it's 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:

Offset timers.png


Uses and examples

Enable/disable triggers

This'll make use of tempTimer to enable a trigger and disable it after a short period of time:

enableTrigger("Get enemy list")
tempTimer(3, [[disableTrigger("Get enemy list")]])

Running a script after the current triggers

A useful trick to get your code to run right after all of the current triggers (GUI and temporary) ran would be to use a time of 0:

-- in a script, this will run after all scripts were loaded - including the system, wherever in the order it is.
tempTimer(0, function()
  function svo.dl_prompttag2()
    if not svo.defc.dragonform or not svo.lasthit or not svo.dl_list or not svo.dl_list[svo.lasthit] then return "" end
    local t = svo.dl_list[svo.lasthit]
    return string.format("%s: h %d|t %d|ra %d|la %d|rl %d|ll %d", svo.lasthit, t.head, t.torso, t.rightarm, t.leftarm, t.rightleg, t.leftleg)
  end
  svo.adddefinition("@dl_prompttag2", "svo.dl_prompttag2()")
end)

Have more examples you'd like to see! Please add or request them!

Mapper

Maps and Autowalking

Maps are implemented as directed graphs of connected nodes (rooms). Nodes are connected by edges (exits). Nodes are referenced by unique integer IDs. Edges fall into 2 categories: Standard exits with a visual representation on the map (e. g. north, south) and "special exits" without a calculated visual representation on the map e. g. the command "jump cliff" is a special exit that connects to a room without a clear spatial orientation. However, special exits can be visually represented if the user provides custom exit line strips. Standard exits are referenced by their respective node and a directional integer value. Special exits are referenced by their respective nodes and strings that hold the exit commands. Both nodes and individual exits can seperately be locked and thus excluded from speed walk path finding graphs. Path finding uses the fast A* search algorithm. Mudlet choses a path with the fastest travel time (-> room weights) as opposed to the shortest path.

Maps are divided into areas or zones where the area/room relationship is unique, i. e. rooms cannot be in more than 1 area.

Note Note: Areas help make do with the typical geographical irregularities of MUD 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 MUD. 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, but the visual map editor only works in regular mode. Consequently, grid map mode need to be turned off before editing the map. Grid mode is an area property.

regular mode regular mode

Areas

Areas are defined by a unique integer number ID and a unique area name. Mudlet builds an internal numerical area ID table on the basis of the rooms that belong to the respective areas. Mudlet keeps a seperate lookup table to retrieve the area name on the basis of the area IDs. This name lookup table is not guaranteed to be correct because it may be imported invalid information if the map has been downloaded by the game server as an xml map description file on the basis of the MMP protocol. [1] However, if the map has been created with Mudlet directly, there will be no such problems as the area name lookup table API is made to enforce uniqueness.

Area Properties

  • area map display mode (-> regular map display mode or grid mode)
  • area name

Rooms

Rooms are invisible on the map unless the required properties have been set.

Room Properties

  • Room object need following required properties in order to be shown on the respective area map:
    • unique room ID in form of an integer value
    • area ID in form of an integer value (To which area does this room belong - or in other words, which area map displays this room)
    • x, y and z coordinates as integer values which relate to its paricular area map coordinate system
  • Optional room properties:
    • regular exits with or without respective exit locks
    • special exits with or without respecitve special exit locks
    • room lock
    • exit stubs (draw exit directions even though the exit rooms have not yet been defined)
    • custom exit lines (user defined line strips of various formats to visualize special exits or redefine regular exit lines)
    • searchable room name that can be used for bookmarks, annotations etc.
    • room weight (How long does it travel through this node. A high room weight makes it less likely that this room will be chosen for pathfinding e. g. a safe road should have a low weight, whereas a dangerous place should have a high weight
    • room color
    • room character e. g. the symbol $ to symbolize a bank or H for a hotel.

Advanced Map Features

Map Labels

Maps can be embellised 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).

misc label types zoomed label as background image

(The desert and dragon images used in this example are licensed under the Creative Commons Attribution 2.0 Generic license and can be found here: http://en.wikipedia.org/wiki/File:Ninedragonwallpic1.jpg and http://en.wikipedia.org/wiki/File:Siwa_sand_dunes2009a.jpg)

Custom Exit Line Definitions

The mapper supports user defined visual exit lines on the basis of a sequence of line points in the map coordinate system. Custom lines as well as labels work on real numbers to allow for fine grained placement. User defined lines can be solid, dotted, dashed etc. line types with or without ending arrows. The line color can be freely selected. By default the regular exit color is being used.

custom exit line demo custom exit line demo

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.

Visual Map Editor

Maps can be comfortably edited by using the visual map editor or by scripts. The editor behaves like the usual WYSIWYG editors. Select objects with a left click and then right click to open a context menus and do actions on the selected objects.

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

Mapping Tutorial

Mapping Special Cases

This is a quick guide on ways to handle special movement scenarios.

Exit Scripts

Some of the following scripts depend on this functionality. This serves to execute a script if a given exit is sent. For instance in the speedwalk function, every direction before being sent can call this function.

function checkExitScript(room, dir)
        --room is the room id #, dir is the direction we are attempting
	local exitScript = getRoomUserData(room, "exitScript"..dir)
	if exitScript ~= "" then
		assert(loadstring(exitScript)) ()
	end
end

Delayed Movements

This approach can be used for things such as waiting for a ship to arrive. It depends on the exitScript function above being defined.

Alias: ^pauseUntil "(.+)" (.+)$

Usage: pauseUntil "board ship" A ship sails into port.$

Script:

setRoomUserData(roomid, "exitScript"..matches[2], "moveStop=1;tempTrigger("..matches[3]..", [[moveStop=nil;speedWalkPath = roomsToWalk;doSpeedWalk()]],true)")

The moveStop=1 causes my speedwalker to stall, the tempTrigger part triggers the action to continue walking. When a message such as "A ship sails into port" on which the direction "board ship" will be launched. Similarly the exit "disembark ship" will pause the mapper until the message indicating we've landed has been seen. Note that because we check the exitScripts BEFORE moving a direction this allows us to wait.

Non-Standard Room Entrances

Sometimes we move in non-standard ways, such as teleportation that might not give a standard room description to trigger a movement off. However there is usually other information.

Alias: ^automove "(.+)" .+$

Usage: automove "enter chamber" You try to enter the chamber, but a trap door opens, sending you spiraling into darkness!

This once again makes use of the exitScript function, script:

setRoomUserData(roomid, "exitScript"..matches[2], "tempTrigger("..matches[3]..", [[onFollow(nil)]],true)")

onFollow() is another function I have which monitors the queue of directions to move. How I setup this function, nil means attempt to move from the current room to the next room id.

Mapping Temporary Areas

This is rather easy, simply set a variable, let's call it "tempRoom" and in your room creation code, set a piece of UserData to that value. Then use an alias to search through the UserData for rooms with that flag and delete them. This is useful for dynamic areas that change such as ones that are randomly generated on a mud reboot.

Mapper tips

Placing the mapper into a corner

Here's a snippet you can use to place the mapper window into a corner and have it automatically come up whenever you open Mudlet. To use this, create a new script (you can make it anywhere) and copy/paste the code into it.

local main = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="mapper container"})
 
local mapper = Geyser.Mapper:new({
  name = "mapper",
  x = "70%", y = 0, -- edit here if you want to move it
  width = "30%", height = "50%"
}, main)

Mapper Favorites

This post here describes how to add a right click menu to your mapper filled with rooms to speedwalk to.

Screenshots

Mapper 562.png Mudlet 563.png

TK6fS.png

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.

Handling Tables in Lua

A good overview of tables is available on Lua's wiki in the TablesTutorial. Nick Gammon has also written a nice overview on how to deal with Lua tables.

How to use multilinematches[n][m]

multilinematches[n][m] is the compliment of matches[n] when matching multi-line triggers. multilinematches[n][m] stores its matches by lines, inside each line are the relevant matches to it. TThe following example can be tested on the MUD batmud.bat.org:

In the case of a multiline trigger with these 2 Perl regex as conditions:

^You have (\w+) (\w+) (\w+) (\w+)

^You are (\w+).*(\w+).*

The command "score" generates the following output on batMUD:

 You have an almost non-existent ability for avoiding hits.
 You are irreproachably kind.
 You have not completed any quests.
 You are refreshed, hungry, very young and brave.
 Conquer leads the human race.
 Hp:295/295 Sp:132/132 Ep:182/181 Exp:269 >

If you add this script to the trigger:

showMultimatches()

The script, i.e. the call to the function showMultimatches() generates this output:

 -------------------------------------------------------
 The table multimatches[n][m] contains:
 -------------------------------------------------------
 regex 1 captured: (multimatches[1][1-n])
           key=1 value=You have not completed any quests
           key=2 value=not
           key=3 value=completed
           key=4 value=any
           key=5 value=quests
 regex 2 captured: (multimatches[2][1-n])
           key=1 value=You are refreshed, hungry, very young and brave
           key=2 value=refreshed
           key=3 value=young
           key=4 value=and
           key=5 value=brave
 -------------------------------------------------------

The function showMultimatches() prints out the content of the table multimatches[n][m]. You can now see what the table multimatches[][] contains in this case. The first trigger condition (=regex 1) got as the first full match "You have not completed any quests". This is stored in multimatches[1][1] as the value of key=1 in the sub-table matches[1] which, in turn, is the value of key=1 of the table multimatches[n][m].

The structure of the table multimatches:

multimatches {
                1 = {
                       matches[1] of regex 1
                       matches[2] of regex 1
                       matches[3] of regex 1
                              ...
                       matches[m] of regex 1 },
                2 = {
                       matches[1] of regex 2
                       matches[2] of regex 2
                             ...
                       matches[m] of regex 2 },
                 ...         ...
                n = {
                       matches[1] of regex n
                       matches[2] of regex n
                             ...
                       matches[m] of regex n }
}

The sub-table matches[n] is the same table matches[n] you get when you have a standard non-multiline trigger. The value of the first key, i. e. matches[1], holds the first complete match of the regex. Subsequent keys hold the respective capture groups. For example: Let regex = "You have (\d+) gold and (\d+) silver" and the text from the MUD = "You have 5 gold and 7 silver coins in your bag." Then matches[1] contains "You have 5 gold and 7 silver", matches[2] = "5" and matches[3] = "7". In your script you could do:

myGold = myGold + tonumber( matches[2] )
mySilver = mySilver + tonumber( matches[3] )

However, if you’d like to use this script in the context of a multiline trigger, matches[] would not be defined as there are more than one regex. You need to use multimatches[n][m] in multiline triggers. Above script would look like this if above regex would be the first regex in the multiline trigger:

myGold = myGold + tonumber( multimatches[1][2] )
mySilver = mySilver + tonumber( multimatches[1][3] )

What makes multiline triggers really shine is the ability to react to MUD 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.

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 should a function to listen to, and when the event is raised, the said function(s) will be called. Events can also have function parameters with them, which’ll be passed onto the receiving functions.

Registering an event handler via UI

Registering an event handler means that you’ll be telling Mudlet what function should it call for you when an event is raised, so it’s a two step process - you need to tell it both what function you’d like to be called, and on what event should it be called.

To tell it what function should be called, create a new script, and give the script the name of the function you’d like to be called. This is the only time where an items name matters in Mudlet. You can define the function right inside the script as well, if you’d like.

Next, we tell it what event or events should this function be called on - you can add multiple ones. To do that, enter the events name in the Add User Defined Event Handler: field, press enter, and it’ll go into the list - and that is all.

Registering an event from a script

You can also register your event with the registerAnonymousEventHandler(event name, function name) function inside your scripts:

-- example taken from the God Wars 2 (http://godwars2.org) Mudlet UI - forces the window to keep to a certain size
function keepStaticSize()
  setMainWindowSize(1280,720)
end -- keepStaticSize
 
registerAnonymousEventHandler("sysWindowResizeEvent", "keepStaticSize")

Note Note: Mudlet also uses the event system in-game protocols (like ATCP, GMCP and others).

Note Note: Event handler functions can now also be in namespaces (tables).

Raising an event

To raise an event, you’d use the raiseEvent function:

raiseEvent(name, [arguments...])

It takes an event name as the first argument, and then any amount of arguments after it which will be passed onto the receiving functions.

Mini-tutorial

As an example, our prompt trigger could raise an onPrompt event if you want to attach 2 functions to it. In your prompt trigger, all you’d need to do is raiseEvent("onPrompt"). Now we go about creating functions that attach to the event - lets say the first one is check_health_stuff() and the other is check_salve_stuff(). We would like these to be executed when the event is raised. So create a script and give it a name of check_health_stuff. In the Add user defined event handler, type onPrompt, and press enter to add it to the list. In the script box, create:

function check_health_stuff()
  echo("I work!\n")
end

When the onPrompt event comes along, that script catches it, and runs check_health_stuff() for you.

Link title

Mudlet-raised events

Mudlet itself also creates events for your scripts to hook on. The following events are generated currently:

mapOpenEvent

Raised when the mapper is opened - either the floating dock or the in-Mudlet widget.

sysWindowResizeEvent

Raised when the main window 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:

function resizeEvent( event, x, y )
  echo("RESIZE EVENT: event="..event.." x="..x.." y="..y.."\n")
end

sysWindowMousePressEvent

Raised when a mouse button is pressed down anywhere on the main window (note that a click is composed of a mouse press and mouse release). The button number and the x,y coordinates of the click are reported. Example

function onClickHandler( event, button, x, y )
  echo("CLICK event:"..event.." button="..button.." x="..x.." y="..y.."\n")
end

sysWindowMouseReleaseEvent

Raised when a mouse button is released after being pressed down anywhere on the main window (note that a click is composed of a mouse press and mouse release). See sysWindowMousePressEvent for example use.

sysLoadEvent

Raised when Mudlet is loading the profile. Note that when it does so, it also compiles and runs all scripts - which could be a good idea to initialize everything at, 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.

sysExitEvent

Raised when Mudlet is shutting down the profile - a good event to hook onto for saving all of your data.

sysDownloadDone

Raised when Mudlet is finished downloading a file successfully - the location of the downloaded file is passed as a second argument. For a practical example, see the downloadFile() function.

sysDownloadError

Raised when downloading a file failed - the second argument contains the error message. Starting with Mudlet 2.0-test5+, it specifies the original URL that was going to be downloaded.

sysIrcMessage

Raised when you see or receive an IRC message. The speakers name, channel and their message will follow as arguments.

function onIrcMessage(_, person, channel, message)
  echo(string.format('(%s) %s says, "%s"\n', channel, person, message))
end

Added to Mudlet in an unreleased 2.0rc8

sysDataSendRequest

Raised right before a command from the send() function or the command line is sent to the game - useful for keeping track of what your last command was, or even denying the command to be sent if necessary with denyCurrentSend().

Note: if you'll be making use of denyCurrentSend(), you really should notify the user that you denied their command - unexperienced ones might conclude that your script or Mudlet is buggy if they don't see visual feedback. Do not mis-use this and use it as keylogger either.

function onNetworkOutput(_, command)
  if math.random(2) == 1 then
    echo("Hello! Sending "..command.." to the game.\n")
  else
    echo("Not your day! Denying "..command..".\n")
  end
end

sysConnectionEvent

Raised when the profile becomes connected to a MUD - available in 2.0-test5+.

sysDisconnectionEvent

Raised when the profile becomes disconnected, either manually or by the game - available in 2.0-test5+.

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. Available in 2.1+

sysMapDownloadEvent

Raised whenever an MMP map (currently only supported by IRE games) is downloaded and loaded in.

Supported Protocols

Mudlet supports GMCP, ATCP, Aardwolfs 102 and and the MXP Protocol. MXP, ATCP and 102 are enabled by default, while GMCP can be enabled in settings.

GMCP

GMCP is a protocol for MUD servers to communicate information with MUD 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 GMCP by clicking on the Settings button (or Options->Preferences in the menu, or <alt>p). The option is on the General tab. Once GMCP is enabled, you will need to reconnect to the MUD so that Mudlet can inform the server it is ready to receive GMCP information. Mudlet will automatically enable some GMCP modules for you once GMCP has been enabled. To get an idea of what information is available, you can use

display(gmcp)

When working with GMCP on IRE games, their GMCP reference is a useful tool.

Using GMCP

Receiving GMCP Data

To "trigger" on GMCP messages, you'll need to create an event handler - Mudlet will call it for you whenever relevant GMCP data is received.

As an example, create a new script and give it a name of the function you'd like to be called when the relevant GMCP message is received. Then, add the GMCP event you'd like the function to fire on under the registered event handlers left. Lastly, define the function - either in this or any other script - and you'll be done. The GMCP data received will be stored in the corresponding field of the gmcp table, which your function will read from.

Example:

Using gmcp.png

The test_gmcp() function will be called whenever Char.Vitals is received from the game, and it'll echo the latest data on the screen.

Sending GMCP Data

Certain modules will only send data when a request is made by your client. In Mudlet, you can make such a request using the command sendGMCP("command"). Read your MUD's relevant documentation, such as the IRE document on GMCP, for information about specific modules.

See Also: sendGMCP

Managing GMCP Modules

While some GMCP modules are enabled by Mudlet by default when you connect with a GMCP enabled MUD, others may not be 'standard' modules and are instead specific to the MUD itself. In order to provide a way to manage GMCP modules without scripts causing modules in use by other scripts to be disabled. Note Note: The gmod lua module has been included with Mudlet (rc2.0+).

Registering User

While this step is no longer strictly required, you can register your 'user' with gmod using

gmod.registerUser("MyUser")

Where MyUser is your plugin/addon/whatever name. However, your user will be automatically registered if you enable or disable any modules using it. Which leads us to...

Enabling Modules

Enabling a GMCP module is as easy as:

gmod.enableModule("MyUser", "Module.Name")

If MyUser has not been registered previously, then they will be automatically registered when you call this function. An example of a module which would need to be enabled this way is the IRE.Rift module provided by IRE MUDs.

-- add this to a login trigger, or anything that will get done just once per login
gmod.enableModule("<character name>", "IRE.Rift")

Another example would be the Combat module in Lithmeria, which isn't enabled by default:

-- add this to a login trigger, or anything that will get done just once per login
gmod.enableModule("<character name>", "Combat")

Disabling Modules

Disabling a GMCP module is just as easy as enabling it:

gmod.disableModule("MyUser", "Module.Name")

The main difference being that the module will be turned on as soon as you enable it if it is not already enabled. If you disable it, it will not be disabled with the server until every user of that module has disabled it. This prevents script A from disabling modules that script B may still be using.

Thorough GMCP tutorial

A good GMCP tutorial that walks you through receiving and sending GMCP data is available here - take a read!

ATCP

Since version 1.0.6, Mudlet includes support for ATCP. This is primarily available on IRE-based MUDs, but Mudlets impelementation is generic enough such that any it should work on others.

The latest ATCP data is stored in the atcp table. Whenever new data arrives, the previous is overwritten. An event is also raised for each ATCP message that arrives. To find out the available messages available in the atcp table and the event names, you can use display(atcp).

Note that while the typical message comes in the format of Module.Submodule, ie Char.Vitals or Room.Exits, in Mudlet the dot is removed - so it becomes CharVitals and RoomExits.

Example
room_number = tonumber(atcp.RoomNum)
echo(room_number)

Triggering on ATCP events

If you’d like to trigger on ATCP messages, then you need to create scripts to attach handlers to the ATCP messages. The ATCP handler names follow the same format as the atcp table - RoomNum, RoomExits, CharVitals and so on.

While the concept of handlers for events is to be explained elsewhere in the manual, the quick rundown is this - place the event name you’d like your script to listen to into the Add User Defined Event Handler: field and press the + button to register it. Next, because scripts in Mudlet can have multiple functions, you need to tell Mudlet which function should it call for you when your handler receives a message. You do that by setting the Script name: to the function name in the script you’d like to be called.

For example, if you’d like to listen to the RoomExits event and have it call the process_exits() function - register RoomExits as the event handler, make the script name be process_exits, and use this in the script:

function process_exits(event, args)
    echo("Called event: " .. event .. "\nWith args: " .. args)
end

Feel free to experiment with this to achieve the desired results. A ATCP demo package is also available on the forums for using event handlers and parsing its messages into Lua datastructures.

Mudlet-specific ATCP

See ATCP Extensions for ATCP extensions that have been added to Mudlet.

Aardwolf’s 102 subchannel

Similar to ATCP, Aardwolf includes a hidden channel of information that you can access in Mudlet since 1.1.1. Mudlet deals with it in the same way as with ATCP, so for full usage instructions see the ATCP section. All data is stored in the channel102 table, such that you can do:

display(channel102)

... to see all the latest information that has been received. The event to create handlers on is titled channel102Message, and you can use the sendTelnetChannel102(msg) function to send text via the 102 channel back to Aardwolf.

-- Function for detecting AFK status on Aardwolf mud.
function amIafk()
   for k,v in pairs(channel102) do
      if k==100 and v==4 then
         return true
      end
   end
   return false
end

MXP

MXP is based loosely on the HTML and XML standards supported by modern web browsers. It is only "loosely" based upon these standards because MUDs require dynamic, streaming text, rather than the page-oriented view of web browsers. Also, the existing standards are needlessly verbose for use on a MUD 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 MUD can exploit this power and cause problems. Certain HTML functions need to be restricted so that MUD 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 MUD 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), pop-up menus, creation of custom elements, line modes, and fg/bg coloring (including bold, italics and underline) - see here for background.

Adding support for a telnet protocol

In addition to supporting ATCP, GMCP, Aardwolf's 102 and MXP, Mudlet has open telnet support - meaning that for any telnet protocol it doesn't support, it has the tools you can use to build the support for. This does not mean Mudlet supports other protocols "out of the box" - you will either have to get code that adds the support, or you could create it yourself.

The basic tools that you need are addSupportedTelnetOption(), sendSocket() and the sysTelnetEvent.

Create an event handler that goes off on sysTelnetEvent - which is raised whenever an unsupported telnet option is encountered. Your logic handling will start in this event handler. Once you decide what you'd like to send to the MUD, 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 MUD server. See this MSDP snippet for a barebones example.

API philosophy

Adding a support for a new telnet protocol will involve adding the user-facing API. It best for users if it was in the same style as Mudlets handling of other protocols. To see how it's done exactly, check out GMCP, ATCP or Aardwolf 102 examples - but the gist of it is provided below.

Mudlet has a built-in event system, which is used to broadcast messages in an independent way. With it, people can "trigger" on 102, ATCP or GMCP events with Lua functions that get called whenever an event they're interested in is raised. Use the event system to provide your users with a way to react to new protocol data.

Events have names, and optionally, any amount of data with them. For protocol support, Mudlet prefixes the relevant message received name with the protocol name in lowercase. For example, an ATCP Char.Vitals getting updated would raise an event titled "atcp.Char.Vitals". A GMCP Room.Info message would raise a "gmcp.Room.Info" message.

Additionally, Mudlet also allows catch-all event - in case the user wants to use one event handler for a variety of sub-events (it's not uncommon for MUDs to use Main.Sub.Add, Main.Sub.Remove, Main.Sub.List to keep track of a list, for example, while conserving data). To accomplish this, it raises events for every relevant namespace - that is, a Main.Sub.Add event will raise protocol.Main.Sub and protocol.Main.Sub.Add events. While it is entirely possible for one event handler to react to multiple events, this is provided for convenience.

For storing protocol data, Mudlet uses an aptly named global table - gmcp for GMCP data, atcp for ATCP data. Data is stored in the same way it is received and the event is raised for - so a Char.Vitals message's contents will be stored in gmcp.Char.Vitals, a Room.Info's contents in gmcp.Room.Info. If there were was any nested data within the message, it is stored as a table within the proper namespace - ie, a "details" JSON array of a GMCP Room.Info message would be stored in gmcp.Room.Info.details. Use a global table with the protocol name in lowerspace for storing permanent data that your users will read from.

That's it! If you'll need any Mudlet-related help, feel free to post on our forums. Once you're done, package your work for distribution which you can optionally post in the finished scripts section.

Scripting with Mudlet

Lua tables can basically be considered multidimensional arrays and dictionaries at the same time. If we have the table matches, matches[2] is the first element, matches[n+1] the n-th element.

 a = "Tom"
 matches[2] = "Betty"
 b = matches[2]
 c = a .. b and e will equal "TomBetty"

To output a table you can use a convenience function - display(mytable), which is built into Mudlet.

Lua interface functions to Mudlet - or how do I access triggers, timers etc. from Lua scripts

How to get data from regex capture groups? Regular expression capture groups (e.g. "(\d+)" ) are passed on to Lua scripts as a Lua table matches. To make use of this information inside Lua scripts, you need to specify the number of the capture group within the regex.

Example: You have (\d+) weapons and they are (?:(\b\w+\W+)+)

This regex contains 3 capture groups, but only the 2 green colored ones contain data as the red capture group is a non-capturing group. Consequently, your Lua script gets passed only 2 instead of 3 capture groups and matches[4] is undefined.

In your Lua script you may write following program in order to print the number and status of your weapons on the screen:

You have (\d+) weapons and they are (?:(\b\w+\W+)+)

 number_of_weapons = matches[2]
 status_of_weapons = matches[3]
 notice = number_of_weapons .. status_of_weapons
 echo( notice )
 send( "put weapons in backpack" )
 
 -- the following 2 lines color the first capture
 -- group red and the second group blue
 -- see below for details
 
 selectCaptureGroup( 2 )
 setFgColor( 255,0,0 )
 
 selectCaptureGroup( 3 )
 setFgColor( 0,0,255 )

The best way is to use selectCaptureGroup( number ) to select the proper capture group and then perform your actions on it e.g. replace(), highlight etc. Note: Both selectCaptureGroup() and matches[n] start with group 1 (which is the whole match. The defined capture groups start with 2).

How to select all occurrences of "Tom" and highlight them?

You add a function like this to a script containing you main function definitions. Note that script items differ from all other "scripts" in triggers, timers, actions etc. because they require you to put your code in proper functions that can be called by your other trigger-scripts, timer-scripts etc. via normal function calls. Trigger-scripts, timer-scripts etc. cannot contain any function definitions because they are automatically generated functions themselves because this makes usage a lot easier.

To come back to our question how to select all occurrences of "Tom" and highlight them:

  function setBgColorAll( word, r, g, b )
    i = 0
    word_count = 1
    while i > -1 do
        i = selectString(word, word_count)
        if i == -1 then
             return
        end
        word_count = word_count +1
        setBgColor( r, g, b )
    end
  end

Then you simply define a substring matching trigger on the word "Tom" and in the trigger script you call above function:

setBgColorAll("Tom", 255,50,50)

Sending commands to the MUD or printing information messages on the screen

To print information messages on the session screen you can use the echo( message ) function, or insertText( text ). Currently, it only takes one string as argument.

To send a command to the MUD, you can use the send( command ) function. In Alias scripts the command that is being sent to the MUD is contained in the variable command that you can change in the context of Alias scripts. Alias take regular expressions, as well. As a result, you can use following regex and script to talk like Yoda: Perl regex:

say (\w+).*(\w*).*(.*)

script:

send( "say " .. matches[4] .." " .. matches[2] .." ".. matches[3] )

Note: The variable "command" contains what was entered in the command line or issued via the expandAlias( ) function. If you use expandAlias( command ) inside an alias script the command would be doubled. You have to use send( ) inside an alias script to prevent recursion. This will send the data directly and bypass the alias expansion.

Changing text from the MUD or reformatting text (highlight, make bold etc.)

When sending commands to the MUD - from now on referred to as output stream - alias scripts find the command that was issued by the user stored in the variable "command".

By manipulating the value, the command can easily be changed before it is being sent to the MUD.

However, things get much more complicated with the data received from the MUD – from now on referred to as input stream. Before triggers can be run on the MUD data, Mudlet has to strip all format codes from the text and store it in data structures associated with the text. Consequently, the text that is being passed on to the trigger processing unit is a small subset of the data received from the MUD. If you want to edit, replace, delete or reformat text from within your trigger scripts you have to keep this in mind if you don’t want to lose all text format information such as colors etc.

As the text is linked with data structures containing the format of the text, the cursor position inside the line is important if data is being changed. You select a word or a sequence of characters from the line and then issue commands to do actions on the selected data.

Replacing the word "Tom" with "Betty" in the line: Jim, Tom and Lucy are learning a new spell. This could be done with following script:

selectString("Tom",1)
replace("Betty")

Things get more complicated if there are two or more occurrences of "Tom" in the line e.g. Jim and Tom like magic. Jim, Tom and Lucy are learning a new spell.

The above example code would select the first occurrence of "Tom" in this line and ignore the second. If you want to work on the the second occurrence of "Tom" you have to specify the occurrence number in the call to select().

selectString( "Tom", 2 )
replace( "Betty" )

This code would change the second "Tom" and leave the first "Tom" alone. The function call

replaceAll( "Betty" )

will replace all occurrences of "Tom" with "Betty" in the line if "Tom" has been selected before. replaceAll() is a convenience function defined in LuaGlobal.lua.

Colorization example: You want to change to color of the words "ugly monster" to red on a white background.

You add a new trigger and define the regex: ugly monster In the script you write:

selectString("ugly monster", 1 )
setFgColor(255,0,0)
setBgColor(255,255,255)
resetFormat()

Another means to select text is to select a range of characters by specifying cursor positions. If we have following line: Jim and Tom like magic. Jim, Tom and Lucy are learning a new spell.

selectSection( 28, 3 )

This example would select the second Tom. The first argument to selectSection is the cursor position within the line and the second argument is the length of the selection.

selectCaptureGroup( number )

This function selects the captureGroup number if you use Perl regular expressions containing capture groups. The first capture group starts with index 1.

Deleting Text - Gagging

deleteLine()

This function deletes the current line - or any line where the cursor is currently placed. You can use repeated calls to this function to effectively erase the entire text buffer. If you want to delete or gag certain words only, you can select the text that you want to delete and then replace it with an empty string e.g:

If you get this line form the MUD: "Mary and Tom walk to the diner."

selectString( "Tom", 1 )
replace( "" )

Then the output will be changed to: "Mary and walk to the diner."

Cursor Movement and Cursor Placement

Mudlet allows you to insert text arbitrarily within the buffer - in the previous line, in the previous ten lines, or even the first line that you've ever saw. These are the tools to help you with the job:

moveCursor( windowName, x, y ) This will move the user cursor of window windowName to the absolute (x/y) coordinates in the text.

moveCursor( "main", 20, 3950 ) will move the cursor on the 20th character from the left on line number 3950. To determine the current cursor position you can use getLineNumber() and getColumnNumber() as well as getLastLineNumber() to get the number of the last line in the text buffer. moveCursorEnd("main") will move the cursor of the main display to end of the buffer. This is always a new line of size 1 containing the character \n.

number_of_last_line_in_text = getLineCount() returns the number of the last line of the text in the console buffer. This number will change as soon as a new \n is printed either by the user or when a new line arrives from the MUD. All lines from the MUD are terminated with \n which is called line feed or the new line character. This control character ends the current line and move the cursor to the beginning of the next line, thus creating a new, empty line below the line that contains the \n.

line_number_of_the_current_cursor_position = getLineNumber()

column_number_of_the_current_cursor_position = getColumnNumber()

luaTable_containing_textlines = getLines( absolute_line_number_from, absolute_line_number_to ) this will return a Lua table containing all lines between the absolute positions from and to.

Note Note: This function uses absolute line numbers, not relative ones like in moveCursor().

moveCursor() returns true or false depending on whether the move was possible and done.

Inserting text in the middle of the line

Here's an example where we'll append the text (one) right after the word exit in the line of You see a single exit leading west.

Inserting text.png

The pattern we used was an exact match for You see a single exit leading west. and the code is:

if moveCursor(string.find(line, "exit")+#("exit")-1, getLineNumber()) then
  insertText("(one)")
end

What happened here:

  • we triggered on the desired line using our pattern above
  • we used moveCursor() to place the cursor in the desired position within the line. moveCursor() takes both the line number and the position within the line to place our virtual cursor on, so
    • we used string.find() to find the position of the word "exit" within the line
    • but string.find() returns us the position of the first character of the word we want, while we want to have the text be right after it - so we find out how long our word is with #("exit"), add that to the number returned by string.find() which gets us the first character + the length of the word - which isn't quite at the end of the word, but the word plus the space (because of string.find() and the first character) - so we substract 1 to move our cursor right at the end of the word
    • we then use getLineNumber() to get the current line number, so our cursor is placed on the current line, at our desired position
  • lastly we finally insert the text with insertText(), which puts the text exactly where our virtual cursor is

Done! You can also use cinsertText() for coloured inserts, and other functions mentioned above and in the API manual to help you do what you'd like.

User defined dockable windows

You may want to use dock windows to display information you gathered in your scripts, or you may want to use them as chat windows etc. Adding a user defined window:

openUserWindow( string window_name )

echoUserWindow( string window_name, string text )

setWindowSize( int x, int y )

clearWindow( string window_name )

Please note that these have been depricated in favour of embedded miniconsoles, as those integrate more seamlessly into the UI. User Windows still work fine, however, as we don't break scripts (backwards compatibility) in Mudlet.

Dynamic Triggers

triggerID = tempTrigger( substring pattern, code ) creates a fast substring matching trigger

triggerID = tempRegexTrigger( regex, code ) creates a regular expression matching trigger

triggerID = tempBeginOfLineTrigger( begin of line pattern, code ) creates a fast begin of line substring trigger

Scripting howtos

How to convert a string to value?

Say you'd like to capture a number from a trigger, but the capture always ends up being a "string" (or, just text on which you can't do any maths on) even if it's a number. To convert it to a number, you'd want to use the tonumber() function:

myage = tonumber(matches[2])

How to highlight my current target?

You can put the following script into your targetting alias:

if id then killTrigger(id) end
id = tempTrigger(target, [[selectString("]] .. target .. [[", 1) fg("gold") deselect() resetFormat()]])

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, [[selectString("]] .. target .. [[", 1) fg("gold") deselect() resetFormat()]])

How to format an echo to a miniConsole?

One of the ways you can create multi-line displays in a miniConsole with variable information is with string.format and the use of [[ ]] brackets for text, which allow for multiple line in text:

local WindowWidth, WindowHeight = getMainWindowSize();
createMiniConsole("sys",WindowWidth-650,0,650,300)
 
local name, age, sex = "Bob", 34, "male"
 
cecho("sys", string.format([[
 
  /---------\
      %s
   %dyrs
   sex - %s 
  \---------/
]], name, age, sex))

How to play a sound when I receive communication while afk?

Play sound when afk trigger.png

For this to work, place the line you'd like to trigger on in the first pattern box and select the appropriate pattern type. Then add return not hasFocus() with the Lua function as the second pattern, enable the AND trigger, and set the line delta to zero. Then just enable play sound, choose your sound and you're set!

How can I make a key that toggles between commands?

To make a key that toggles between two actions, for example - sleep/wake, you can use this as the script:

if not sleeping then
  send("sleep")
  sleeping = true
else
  send("wake")
  sleeping = false
end

How can I make a trigger that goes off only if the next line is not a particular one?

Here's how you can set it up - replace line1 and line2 with appropriate lines.

Trigger multiline not another example.png

Here's the Mudlet XML you can download for this!

Advanced scripting tips

Do stuff after all triggers/aliases/scripts are run

This little snippet will have your commands be executed right after, depending on the context you run it in, all triggers, aliases or scripts are completed:

tempTimer(0, [[mycode]])

How to delete the previous and current lines

This little snippet comes from Iocun:

moveCursor(0,getLineCount()-1)
deleteLine()
moveCursor(0,getLineCount())
deleteLine()

db: Mudlet's database frontend

The DB package is meant to provide easier access to a database, so you don’t have to know SQL or use the luasql module to set and get at your data. However, it does require that the luasql module be compiled and included in Mudlet to function - and this all is available since Mudlet 1.0.6.

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, ths would mean that you’d define what goes into each column. A simple example:

db:create("people", {friends={"name", "city", "notes"}, enemies={"name", "city", "notes"}})

This will create a database which contains two sheets: one named friends, the other named enemies. Each has three columns, name, city and notes-- and the datatype of each are strings, though the types are very flexible and can be changed basically whenever you would like. It’ll be stored in a file named Database_people.db in your Mudlet config directory on the hard drive should you want to share it.

It’s okay to run this function repeatedly, or to place it at the top-level of a script so that it gets run each time the script is saved: the DB package will not wipe out or clear the existing data in this case. Note that adding new columns to an existing database currently doesn't work in Mudlet 2.1 - see db:create() on how to deal with this.

A note on column or field names: you may not create a field which begins with an underscore. This is strictly reserved to the db package for special use.

Adding Data

To add data to your database, you must first obtain a reference (variable) for it. You do that with the db:get_database function, such as:

  local mydb = db:get_database("people")

The database object contains certain convenience functions (discussed later, but all are preceded with an underscore), but also a reference to every sheet that currently exists within the database. You then use the db:add() function to add data to the specified sheet.

  db:add(mydb.friends, {name="Ixokai", city="Magnagora"})

If you would like to add multiple rows at once to the same table, you can do that by just passing in multiple tables:

  db:add(mydb.friends,
    {name="Ixokai", city="Magnagora"},
    {name="Vadi", city="New Celest"},
    {name="Heiko", city="Hallifax", notes="The Boss"}
  )

Notice that by default, all columns of every table are considered optional-- if you don’t include it in the add, then it will be set to its default value (which is nil by default)

For those familiar with databases: with the DB package, you don’t have to worry about committing or rolling back any changes, it will commit after each action automatically. If you would like more control then this, see Transactions below.

You also cannot control what is the primary key of any sheets managed with DB, nor do you have to create one. Each row will get a unique integer ID that automatically increments, and this field can be accessed as "_row_id".

Querying

Putting data in isn’t any fun if you can’t get it out. If you want every row from the sheet, you can do:

  db:fetch(mydb.friends)

But rarely is that actually useful; usually you want to get only select data. For example, you only want to get people from the city of Magnagora. To do that you need to specify what criteria the system should use to determine what to return to you. It looks like this:

  db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"))

So the basic command is - db:fetch(_sheet_, _what to filter by_)

The following filter operations are defined:

  db:eq(field, value[, case_insensitive]) -- Defaults to case insensitive, pass true as the last arg to
              reverse this behavior.
  db:not_eq(field, value[, case_insensitive) -- Not Equal To
  db:lt(field, value) -- Less Than
  db:lte(field, value) -- Less Than or  Equal to.
  db:gt(field, value) -- Greater Than
  db:gte(field, value) -- Greater Than or Equal To
  db:is_nil(field) -- If the column is nil
  db:is_not_nil(field) -- If the column is not nil
  db:like(field, pattern) -- A simple matching pattern. An underscore matches any single character,
          and a percent(%) matches zero or more characters. Case insensitive.
  db:not_like(field, pattern) -- As above, except it'll give you everything but what you ask for.
  db:between(field, lower_bound, upper_bound) -- Tests if the field is between the given bounds (numbers only).
  db:not_between(field, lower_bound, upper_bound) -- As above, only... not.
  db:in_(field, table) -- Tests if the field is in the values of the table. NOTE the trailing underscore!
  db:not_in(field, table) -- Tests if the field is NOT in the values of the table *

The db:in_ operator takes a little more explanation. Given a table, it tests if any of the values in the table are in the sheet. For example:

  db:in_(mydb.friends.city, {"Magnagora", "New Celest"})

It tests if city == "Magnagora" OR city == "New Celest", but with a more concise syntax for longer lists of items.

There are also two logical operators:

  db:AND(operation1, ..., operationN)
  db:OR(operation1, operation2)

You may pass multiple operations to db:fetch in a table array, and they will be joined together with an AND by default. For example:

  db:fetch(mydb.friends,
    {db:eq(mydb.friends.city, "Magnagora"), db:like(mydb.friends.name, "X%")}
  )

This will return every record in the sheet which is in the city of Magnagora, and has a name that starts with an X. Again note that in LIKE patterns, a percent is zero or more characters — this is the same effect as "X.*" in pcre patterns. Similarly, an underscore matches any single characters and so is the same as a dot in pcre.

Passing multiple expressions in an array to db:fetch is just a convenience, as its exactly the same as:

  db:fetch(mydb.friends, db:AND(db:eq(mydb.friends.city, "Magnagora"), db:like(mydb.friends.name, "I%")))

The db:OR operation only takes two arguments, and will check to see if either of the two is true. You can nest these logical operators as deeply as you need to.

You can also just pass in a string directly to db:fetch, but you have to be very careful as this will be passed straight to the SQL layer. If you don’t know any SQL then you want to avoid this… for example, in SQL there’s a very big difference between double and single quotes. If you don’t know that, then stick to the db functions. But an example is:

  db:fetch(mydb.friends, "city == 'Magnagora'")

Now, the return value of db:fetch() is always a table array that contains a table dictionary representing the full contents of all matching rows in the sheet. These are standard Lua tables, and you can perform all normal Lua operations on them. For example, to find out how many total items are contained in your results, you can simply do #results. If a request from the friends sheet were to return one row that you stored in the results variable, it would look like this if passed into the display() function:

  table {
  1: table {
    'name': 'Bob',
    'city': 'Magnagora',
    'notes': 'Trademaster of Tailoring'
  }
}

And if you were to echo(#results), it would show 1.

The order of the returned rows from db:fetch is generally the same as the order in which you entered them into the database, but no actual guarantees are made to this. If you care about the order then you can pass one or two optional parameters after the query to db:fetch() to control this.

The first table is an array of fields that indicate the column names to sort by; the second is a flag to switch from the default ascending(smallest to largest) sort, to a descending(largest to smallest) sort. For example:

  db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"), {mydb.friends.city})

This will return all your friends in Magnagora, sorted by their name, from smallest to largest. To reverse this, you would simply do:

  db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"), {mydb.friends.city}, true)

Including more then one field in the array will indicate that in the case that two rows have the same value, the second field should be used to sort them.

If you would like to return ALL rows from a sheet, but still sort them, you can do that by passing nil into the query portion. For example:

  db:fetch(mydb.friends, nil, {mydb.friends.city, mydb.friends.name})

This will return every friend you have, sorted first by city and then their name.

Indexes and Types

The sheets we’ve defined thus far are very simple, but you can take more control over the process if you need to. For example, you may assign default values and types to columns, and the DB package will attempt to coerce them as appropriate. To do that, you change your db:create() call as:

db:create("people", {
  friends={"name", "city", "notes"},
  enemies={
    name="",
    city="",
    notes="",
    enemied="",
    kills=0
  }
})

This is almost the same as the original definition, but we’ve defined that our first four fields are strings with a default value of blank, and the new kills field which is an integer that starts off at 0. The only way to set a datatype is to set a default value at this time.

Please note, beneath the DB package is SQLite, and SQLite is very data-type neutral. It doesn’t really care very much if you break those rules and put an integer in a string field or vice-versa, but the DB package will — to a limited degree — attempt to convert as appropriate, especially for the operations that work on numbers.

You may also create both standard and unique indexes. A unique index enforces that a certain criteria can only happen once in the sheet. Now, before you go and make indexes, pause and consider. There is no right or wrong answer when it comes to what to index: it depends on what kind of queries you do regularly. If in doubt, don’t make an index. Indexes will speed up reading data from the sheet, but they will slow down writing data.

To add an index, pass either the _index or _unique keys in the table definition. An example:

db:create("people", {
  friends={"name", "city", "notes"},
  enemies={
    name="",
    city="",
    notes="",
    enemied="",
    kills=0,
    _index = { "city" },
    _unique = { "name" }
  }
})

Now, bear in mind: _index = { "name", "city"} creates two indexes in this sheet. One on the city field, one on the name field. But, _index = { {"name", "city"} } creates one index: on the combination of the two. Compound indexes help speed up queries which frequently scan two fields together, but don’t help if you scan one or the other.

The admonition against making indexes willy-nilly holds double for compound indexes: do it only if you really need to!

Uniqueness

As was specified, the _unique key can be used to create a unique index. This will make it so a table can only have one record which fulfills that index. If you use an index such as _unique = { "name" } then names must be unique in the sheet. You can specify more than one key to be unique; in that case they will be checked in an OR condition.

Now, if you use db:add() to insert a record which would violate the unique constraint, a hard error will be thrown which will stop your script. Sometimes that level of protection is too much, and in that case you can specify how the db layer handles violations.

There are three possible ways in which the layer can handle such violations; the default is to FAIL and error out.

You can also specify that the db layer should IGNORE any commands that would cause the unique constraint to be violated, or the new data should REPLACE the existing row.

For example:

db:add(mydb.enemies, {name="Bob", city="Sacramento"})
db:add(mydb.enemies, {name="Bob", city="San Francisco"})

With the name field being declared to be unique, these two commands can’t succeed normally. The first db:add() will create a record with the name of Bob, and the second would cause the uniqueness of the name field to be violated. With the default behavior (FAIL), the second db:add() call will raise an error and halt the script.

If you want the IGNORE behavior, the second command will not cause any errors and it will simply fail silently. Bob’s city will still be Sacramento.

With the REPLACE behavior, the second command will cause its data to completely overwrite and replace the first record. Bob’s city will now be San Francisco.

A word of caution with REPLACE, given:

db:add(mydb.enemies, {name="Bob", city="Sacramento", notes="This is something."})
db:add(mydb.enemies, {name="Bob", city="San Francisco"})

With the REPLACE behavior, the second record will overwrite the first-- but the second record does not have the notes field set. So Bob will now not have any notes. It doesn’t -just- replace existing fields with new ones, it replaces the entire record.

To specify which behavior the db layer should use, add a _violations key to the table definition:

db:create("people", {
  friends={"name", "city", "notes"},
  enemies={
    name="",
    city="",
    notes="",
    enemied="",
    kills=0,
    _index = { "city" },
    _unique = { "name" },
    _violations = "IGNORE"
  }
})

Note that the _violations behavior is sheet-specific.

Timestamps

In addition to strings and floats, the db module also has basic support for timestamps. In the database itself this is recorded as an integer (seconds since 1970) called an epoch, but you can easily convert them to strings for display, or even time tables to use with Lua’s built-in time support.

The most common use for the Timestamp type is where you want the database to automatically record the current time whenever you insert a new row into a sheet. The following example illustrates that:

local mydb = db:create("combat_log",
  {
    kills = {
      name = "",
      area = "",
      killed = db:Timestamp("CURRENT_TIMESTAMP"),
      _index = { {"name", "killed"} }
    }
  }
)
 
-- observe that we don't provide the killed field here - DB automatically fills it in for us.
db:add(mydb.kills, {name="Drow", area="Undervault"})
 
results = db:fetch(mydb.kills)
display(results)

The result of that final display would show you this on a newly created sheet:

table {
  1: table {
    '_row_id': 1
    'area': 'Undervault'
    'name': 'Drow'
    'killed': table {
      '_timestamp': 1264317670
    }
  }
}

As you can see from this output, the killed fields contains a timestamp-- and that timestamp is stored as an epoch value in the GMT timezone. For your convenience, the db.Timestamp type offers three functions to get the value of the timestamp in easy formats. They are as_string, as_number and as_table, and are called on the timestamp value itself.

The as_number function returns the epoch number, and the as_table function returns a time table. The as_string function returns a string representation of the timestamp, with a default format of "%m-%d-%Y %H:%M:%S". You can override this format to anything you would like. Details of what you can do with epoch values, time tables, and what format codes you can use are specified in the Lua manual at: http://www.lua.org/pil/22.1.html for the Lua date/time functions.

A quick example of the usage of these functions is:

results = db:fetch(mydb.kills)
for _, row in ipairs(results) do
  echo("You killed " .. row.name .. " at: " .. (row.killed and row.killed:as_string() or "no time") .."\n")
end

Deleting

The db:delete function is used to delete rows from the sheet. It takes two arguments, the first being the sheet you are deleting and the second a query string built using the same functions used to build db:fetch() queries.

For example, to delete all your enemies in the city of Magnagora, you would do:

db:delete(mydb.enemies, db:eq(mydb.enemies.city, "Magnagora"))

Be careful in writing these! You may inadvertantly wipe out huge chunks of your sheets if you don’t have the query parameters set just to what you need them to be. Its advised that you first run a db:fetch() with those parameters to test out the results they return.

As a convenience, you may also pass in a result table that was previously retrieved via db:fetch and it will delete only that record from the table. For example, the following will get all of the enemies in Magnagora, and then delete the first one:

results = db:fetch(mydb.enemies, db:eq(mydb.enemies.city, "Magnagora"))
db:delete(mydb.enemies, db:eq(mydb.enemies._row_id, results[1]._row_id))

That is equivalent to:

db:delete(mydb.enemies, results[1])

You can even pass a number directly to db:delete if you know what _row_id you want to purge.

A final note of caution: if you want to delete all the records in a sheet, you can do so by only passing in the table reference. To try to protect you from doing this inadvertently, you must also pass true as the query after:

db:delete(mydb.enemies, true)

Updating

If you make a change to a table that you have received via db:fetch(), you can save those changes back to the database by doing:

db:update(mydb.enemies, results[1])

A more powerful (and somewhat dangerous, be careful!) function to make changes to the database is db:set, which is capable of making sweeping changes to a column in every row of a sheet. Beware, if you have previously obtained a table from db:fetch, that table will NOT represent this change.

The db:set() function takes two arguments: the field to change, the value to set it to, and the db:fetch() like query to indicate which rows should be affected. If you pass true as the last argument, ALL rows will be changed.

To clear out the notes of all of our friends in Magnagora, we could do:

db:set(mydb.friends.notes, "", db:eq(mydb.friends.notes, "Magnagora"))

Be careful in writing these!

Transactions

As was specified earlier, by default the db module commits everything immediately whenever you make a change. For power-users, if you would like to control transactions yourself, the following functions are provided on your database instance:

local mydb = db:get_database("my_database")
mydb._begin()
mydb._commit()
mydb._rollback()
mydb._end()

Once you issue a mydb._begin() command, autocommit mode will be turned off and stay off until you do a mydb._end(). Thus, if you want to always use transactions explicitly, just put a mydb._begin() right after your db:create() and that database will always be in manual commit mode.

Viewing and editing the database contents

A good tool to view and edit the database contents in raw form is SQlite Sorcerer (free and available for Linux, Windows, Mac).

Debugging raw queries

If you'd like to see the queries that db: is running for you, you can enable debug mode with db.debug_sql = true.

GUI Scripting in Mudlet

Mudlet has extremely powerful GUI capabilities built into it, and with the inclusion of the Geyser and Vyzors layout managers in Mudlet's Lua API it is quicker and easier to get a basic UI created.

Geyser

Geyser is an object oriented framework for creating, updating and organizing GUI elements within Mudlet - it allows you to make your UI easier on Mudlet, and makes it easier for the UI to be compatible with different screen sizes.

Geyser's manual is quite extensive - follow here to read up on it.

UI template

Akaya has created a UI template based on Geyser that can serve as a quick start for customizing the Mudlet interface to your character:

Geyser UI template.png

To get started with it, see UI Template.

Vyzor

Vyzor is a GUI framework that provides an object-oriented interface for Mudlet's Labels and Qt's Stylesheets. It provides Frames (Vyzor's container object) mapped to Mudlet's borders, which update dynamically or maintain a size specified by the user. Users creates Frames, and can define them using values relative to parent Frames; in this way, you can have widgets that properly map to, say, the right side of the main console. All Frames can be filled with Components, which map directly to Stylesheet Properties.

Vyzors homepage is available here; a guide to using it can be found here.

Simple Window Manager

Simple Window Manager is a light-weight script designed to provide the GUI object placement and sizing functionality seen in Geyser and Vyzor without any of the extras. Any GUI object, once created normally, can be added to the SWM along with a corner to base its positioning info off of, the distance from that corner, and the size of the object in any combination of pixels and percentages of the screen. SWM does all the behind the scenes work to keep all objects it has been given to manage in their correct places and sizes as the screen changes size. All other interactions with GUI objects are handled using standard functions built into Mudlet.

Simple Window Managers manual, and download, can be found here.

Useful Resources

There are several useful resources you can refer to when creating your GUI.

Wiki Resources
Excellent for getting an initial feel of how to use the Geyser layout manager.
The GUI section of the Lua API manual
External Resources
The Geyser Layout Manager subforum on Mudlet's forums.
A pinned thread on Mudlet's forums for showing what your GUI looks like. Useful for ideas and to see what is possible.
A forum thread which follows the evolution of the UI provided by God Wars II

Resetting your UI

While scripting your UI, you can reset it completely and have your scripts be loaded from scratch with the resetProfile() function.

Lua API

Global variables

Mudlet defines several global Lua variables that are accessible from anywhere.

Built-in Lua Variables
Variable Name Description
command This variable holds the current user command. This is typically used in alias scripts.
line This variable holds the content of the current line as being processed by the trigger engine. The engine runs all triggers on each line as it arrives from the MUD.
matches[n] This Lua table is being used by Mudlet in the context of triggers that use Perl regular expressions.

matches[1] holds the entire match, matches[2] holds the first capture group, matches[n] holds the nth-1 capture group. If the trigger uses the Perl style /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.

multimatches[n][m] This table is being used by Mudlet in the context of multiline triggers that use Perl regular expression. It holds the table matches[n] as described above for each Perl regular expression based condition of the multiline trigger. multimatches[5][4] may hold the 3rd capture group of the 5th regex in the multiline trigger. This way you can examine and process all relevant data within a single script.

There are other variables that hold MUD-protocol data that are global as well - see Supported Protocols.

Function Categories

Basic Essential Functions: These functions are generic functions used in normal scripting. These deal with mainly everyday things, like sending stuff and echoing to the screen.

Database Functions: A collection of functions for helping deal with the database.

Date & Time Functions: A collection of functions for handling Date & Time.

Display Functions: A collection of functions for displaying or formatting information on the screen.

File System Functions: A collection of functions for interacting with the file system.

Mapper Functions: A collection of functions that manipulate the mapper and it's related features.

Miscellaneous Functions: Miscellaneous functions.

Scripting Object Functions: A collection of arrows that manipulate Mudlets scripting objects - triggers, aliases, and so forth.

Networking Functions: A collection of functions for managing networking.

String Functions: These functions are used to manipulate strings.

Table Functions: These functions are used to manipulate tables. Through them you can add to tables, remove values, check if a value is present in the table, check the size of a table, and more.

UI Functions: These functions are used to construct custom user GUIs. They deal mainly with miniconsole/label/gauge creation and manipulation.

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.

send

send( command, show on screen )
This sends "command" directly to the network layer, skipping the alias matching. The optional second argument of type boolean (print) determines if the outgoing command is to be echoed on the screen.

See also: sendAll()

Note Note: If you want your command to be checked as if it's an alias, use expandAlias() instead - send() will ignore them.

send( "Hello Jane" ) --echos the command on the screen
send( "Hello Jane", true ) --echos the command on the screen
send( "Hello Jane", false ) --does not echo the command on the screen
 
-- use a variable in the send:
send("kick "..target)

echo

echo( windowName, text )
This function appends text at the end of the current line. The current cursor position is ignored. Use moveCursor() and insertText() if you want to print at a different cursor position.
If you'd like to write to a miniconsole instead of the main window, provide its name as the first argument.

Note Note: You can use \n in an echo to insert a new line.

Examples:

echo( "Hello world\n" ) -- writes "Hello world" to the main screen.
echo( "info", "Hello this is the info window" ) -- writes text to the mini console named "info" if such a window exists

Database Functions

These database functions make using a database with Mudlet easier. They are optional, if you are an expert in SQL, you can use LuaSQL's sqlite driver directly within Mudlet - see it's manual 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 an 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)
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.
Example
local mydb = db:get_database("my database")
echo(db:aggregate(mydb.enemies.name, "count"))

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:create

db:create(database name, schema table)
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 reccommended you run this function at a top-level without any kind of guards. If the named database does not exist it will create it. If the database does exist then it will add any columns or indexes which didn’t exist before to that database (note that this does not currently work in Mudlet 2.1 due to a bug in Lua SQL. See below on how to deal with it). If the database already has all the specified columns and indexes, it will do nothing.
The database will be called Database_<sanitized database name>.db and will be stored in the Mudlet configuration directory within your profile folder.
Database tables are called sheets consistantly 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
Example
local mydb = db:create("combat_log",
	{
		kills = {
          	name = "",
          	area = "",
          	killed = db:Timestamp("CURRENT_TIMESTAMP"),
          	_index = { {"name", "area"} }
         	},
          	enemies = {
          		name = "",
                	city = "",
                	reason = "",
                	enemied = db:Timestamp("CURRENT_TIMESTAMP"),
                	_index = { "city" },
                	_unique = { "name" },
                	_violations = "IGNORE"
		}
	})
The above will create a database with two sheets; the first is kills and is used to track every successful kill, with both where and when the kill happened. It has one index, a compound inde 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 unique index is violated. The options you may use are:
  • FAIL - the default. A hard error is thrown, cancelling the script.
  • IGNORE - The command that would add a record that violates uniqueness just fails silently.
  • REPLACE - The old record which matched the unique index is dropped, and the new one is added to replace it.
Returns a reference of an already existing database. This instance can be used to get references to the sheets (and from there, fields) that are defined within the database. You use these references to construct queries.
If a database has a sheet named enemies, you can obtain a reference to that sheet by simply doing:
local mydb = db:get_database("my database")
local enemies_ref = mydb.enemieslocal
local name_ref = mydb.enemies.name

Note Note: db:create() supports adding new columns and indexes to existing databases, but this functionality is currently broken in Mudlet 2.1 due to the underlying Lua SQL binding used being out of date. When you want to add a new column, you have several options:

  • if you are just testing and getting setup, close Mudlet, and delete the Database_<sanitized database name>.db file in your Mudlet folder.
  • if you've already gotten a script and have a fair bit of data with it, or users are already using your script and telling them to delete files on an upgrade is unreasonable, you can use direct SQL to add in a new column. WARNING, this is an expert option, and requires knowledge of SQL to accomplish. You must backup your database file before you start coding this in.
  -- at first, update your db:create schema to have the new field.
  -- then, we'll tell the database to create it if it doesn't exist
 
  -- fetch the data we've got in our sample database
  local test = db:fetch(ndb.db.people)
  -- this requires at least one entry in the database to work
  if next(test) then
    local _,someperson = next(test)
 
    -- in this example, we want to add an order key. If there is no key, means it doesn't exist yet, so it should be added.
    if someperson.order == nil then
      -- do not do the things you see here elsewhere else. This is a big hack/workaround.
      local conn = db.__conn.namedb
      -- order should be a text field, so note that we specify it's type with TEXT and the default value at the end with ""
      local sql_add = [[ALTER TABLE people ADD COLUMN "order" TEXT NULL DEFAULT ""]]
      conn:execute(sql_add)
      conn:commit()
    end
 
    -- here is an another example, in one where we need to add a field that is a number
    if someperson.dragon == nil then
      local conn = db.__conn.namedb
      -- observe that we use the REAL type by default instead and a default of 0
      local sql_add = [[ALTER TABLE people ADD COLUMN "dragon" REAL NULL DEFAULT 0]]
      conn:execute(sql_add)
      conn:commit()
    end
  end

db:delete

db:delete(sheet reference, query)
Deletes rows from the specified sheet. The argument for query tries to be intelligent:
  • If it is a simple number, it deletes a specific row by _row_id
  • If it is a table that contains a _row_id (e.g., a table returned by db:get) it deletes just that record.
  • Otherwise, it deletes every record which matches the query pattern which is specified as with b:get.
  • If the query is simply true, then it will truncate the entire contents of the sheet.
Example
enemies = db:fetch(mydb.enemies)
db:delete(mydb.enemies, enemies[1])
 
db:delete(mydb.enemies, enemies[1]._row_id)
db:delete(mydb.enemies, 5)
db:delete(mydb.enemies, db:eq(mydb.enemies.city, "San Francisco"))
db:delete(mydb.enemies, true)
Those deletion commands will do in order:
  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:
db:set(mydb.enemies, db:exp("kills + 1"), db:eq(mydb.enemies.name, "Ixokai"))
This will increment the value of the kills field for the row identified by the name Ixokai.
But there are other uses, as the underlining database layer provides many functions you can call to do certain things. If you want to get a list of all your enemies who have a name longer then 10 characters, you may do:
db:fetch(mydb.enemies, db:exp("length(name) > 10"))
Again, take special care with this, as you are doing SQL syntax directly and the library can’t help you get things right.

db:fetch

db:fetch(sheet reference, query, order_by, descending)
Returns a table array containing a table for each matching row in the specified sheet. All arguments but sheet are optional. If query is nil, the entire contents of the sheet will be returned.
Query is a string which should be built by calling the various db: expression functions, such as db:eq, db:AND, and such. You may pass a SQL WHERE clause here if you wish, but doing so is very dangerous. If you don’t know SQL well, its best to build the expression.
Query may also be a table array of such expressions, if so they will be AND’d together implicitly.
The results that are returned are not in any guaranteed order, though they are usually the same order as the records were inserted. If you want to rely on the order in any way, you must pass a value to the order_by field. This must be a table array listing the fields you want to sort by. It can be { mydb.kills.area }, or { mydb.kills.area, mydb.kills.name }
The results are returned in ascending (smallest to largest) order; to reverse this pass true into the final field.
Example
db:fetch(mydb.enemies, nil, {mydb.enemies.city, mydb.enemies.name})
db:fetch(mydb.enemies, db:eq(mydb.enemies.city, "San Francisco"))
db:fetch(mydb.kills,
     {db:eq(mydb.kills.area, "Undervault"),
     db:like(mydb.kills.name, "%Drow%")}
)
The first will fetch all of your enemies, sorted first by the city they reside in and then by their name.
The second will fetch only the enemies which are in San Francisco.
The third will fetch all the things you’ve killed in Undervault which have Drow in their name.

db:gt

db:gt(field reference, value)
Returns a database expression to test if the field in the sheet is greater than to the value.

db:get_database

db:get_database(database_name)
Returns your database name.
Example
local mydb = db:get_database("my database")

db:gte

db:gte(field reference, value)
Returns a database expression to test if the field in the sheet is greater than or equal to the value.

db:in_

db:in_(field reference, table array)
Returns a database expression to test if the field in the sheet is one of the values in the table array.
First, note the trailing underscore carefully! It is required.
The following example illustrates the use of in_:
local mydb = db:get_database("my database")
local areas = {"Undervault", "Hell", "Purgatory"}
 
db:fetch(mydb.kills, db:in_(mydb.kills.area, areas))
This will obtain all of your kills which happened in the Undervault, Hell or Purgatory. Every db:in_ expression can be written as a db:OR, but that quite often gets very complex.

db:is_nil

db:is_nil(field reference)
Returns a database expression to test if the field in the sheet is nil.

db:is_not_nil

db:is_not_nil(field reference)
Returns a database expression to test if the field in the sheet is not nil.

db:like

db:like(field reference, pattern)
returns a database expression to test if the field in the sheet matches the specified pattern.
LIKE patterns are not case-sensitive, and allow two wild cards. The first is an underscore which matches any single one character. The second is a percent symbol which matches zero or more of any character.
LIKE with "_" is therefore the same as the "." regular expression.
LIKE with "%" is therefore the same as ".*" regular expression.

db:lt

db:lt(field reference, value)
Returns a database expression to test if the field in the sheet is less than the value.

db:lte

db:lte(field reference, value)
Returns a database expression to test if the field in the sheet is less than or equal to the value.

db:merge_unique

db:merge_unique(sheet reference, table array)
Merges the specified table array into the sheet, modifying any existing rows and adding any that don’t exist.
This function is a convenience utility that allows you to quickly modify a sheet, changing existing rows and add new ones as appropriate. It ONLY works on sheets which have a unique index, and only when that unique index is only on a single field. For more complex situations you’ll have to do the logic yourself.
The table array may contain tables that were either returned previously by db:fetch, or new tables that you’ve constructed with the correct fields, or any mix of both. Each table must have a value for the unique key that has been set on this sheet.
For example, consider this database
local mydb = db:create("peopledb",
     {
          friends = {
               name = "",
               race = "",
               level = 0,
               city = "",
               _index = { "city" },
               _unique = { "name" }
          }
);
Here you have a database with one sheet, which contains your friends, their race, level, and what city they live in. Let’s say you want to fetch everyone who lives in San Francisco, you could do:
local results = db:fetch(mydb.friends, db:eq(mydb.friends.city, "San Francisco"))
The tables in results are static, any changes to them are not saved back to the database. But after a major radioactive cataclysm rendered everyone in San Francisco a mutant, you could make changes to the tables as so:
for _, friend in ipairs(results) do
     friend.race = "Mutant"
end
If you are also now aware of a new arrival in San Francisco, you could add them to that existing table array:
results[#results+1] = {name="Bobette", race="Mutant", city="San Francisco"}
And commit all of these changes back to the database at once with:
db:merge_unique(mydb.friends, results)
The db:merge_unique function will change the city values for all the people who we previously fetched, but then add a new record as well.

db:not_between

db:not_between(field reference, lower_bound, upper_bound)
Returns a database expression to test if the field in the sheet is not a value between lower_bound and upper_bound. This only really makes sense for numbers and Timestamps.

db:not_eq

db:not_eq(field reference, value)
Returns a database expression to test if the field in the sheet is NOT equal to the value.

db:not_in

db:not_in(field reference, table array)
Returns a database expression to test if the field in the sheet is not one of the values in the table array.
See also: db:in_

db:not_like

db:not_like(field reference, pattern)
Returns a database expression to test if the field in the sheet does not match the specified pattern.
LIKE patterns are not case-sensitive, and allow two wild cards. The first is an underscore which matches any single one character. The second is a percent symbol which matches zero or more of any character.
LIKE with "_" is therefore the same as the "." regular expression.
LIKE with "%" is therefore the same as ".*" regular expression.

db:OR

db:OR(sub-expression1, sub-expression2)
Returns a compound database expression that combines both of the simple expressions passed into it; these expressions should be generated with other db: functions such as db:eq, db:like, db:lt and the like.
This compound expression will find any item that matches either the first or the second sub-expression.

db:query_by_eample

db:query_by_example(sheet reference, example table)
Returns a query for database content matching the given example, which can be used for db:delete, db:fetch and db:set. Different fields of the example are AND connected.
Field values should be strings and can contain the following values:
  • literal strings to search for
  • comparison terms prepended with <, >, >=, <=, !=, <> for number and date comparisons
  • ranges with :: between lower and upper bound
  • different single values combined by || as OR
  • strings containing % for a single and _ for multiple wildcard characters

Note Note: Available from Mudlet 3.0 release.

Example
mydb = db:create("mydb",
{
  sheet = {
  name = "", id = 0, city = "",
  _index = { "name" },
  _unique = { "id" },
  _violations = "FAIL"
  }
})
test_data = {
  {name="Ixokai", city="Magnagora", id=1},
  {name="Vadi", city="New Celest", id=2},
  {name="Heiko", city="Hallifax", id=3},
  {name="Keneanung", city="Hashan", id=4},
  {name="Carmain", city="Mhaldor", id=5},
  {name="Ixokai", city="Hallifax", id=6},
}
db:add(mydb.sheet, unpack(test_data))
res = db:fetch(mydb.sheet, db:query_by_example(mydb.sheet, { name = "Ixokai"}))
display(res)
--[[
Prints
{
  {
    id = 1,
    name = "Ixokai",
    city = "Magnagora"
  },
  {
    id = 6,
    name = "Ixokai",
    city = "Hallifax"
  }
}
--]]
mydb = db:create("mydb",
  {
    sheet = {
    name = "", id = 0, city = "",
    _index = { "name" },
    _unique = { "id" },
    _violations = "FAIL"
    }
  })
test_data = {
  {name="Ixokai", city="Magnagora", id=1},
  {name="Vadi", city="New Celest", id=2},
  {name="Heiko", city="Hallifax", id=3},
  {name="Keneanung", city="Hashan", id=4},
  {name="Carmain", city="Mhaldor", id=5},
  {name="Ixokai", city="Hallifax", id=6},
}
db:add(mydb.sheet, unpack(test_data))
res = db:fetch(mydb.sheet, db:query_by_example(mydb.sheet, { name = "Ixokai", id = "1"}))
display(res)
--[[
  Prints
  {
    id = 1,
    name = "Ixokai",
    city = "Magnagora"
  }
--]]

db:set

db:set(field reference, value, query)
The db:set function allows you to set a certain field to a certain value across an entire sheet. Meaning, you can change all of the last_read fields in the sheet to a certain value, or possibly only the last_read fields which are in a certain city. The query argument can be any value which is appropriate for db:fetch, even nil which will change the value for the specified column for EVERY row in the sheet.
For example, consider a situation in which you are tracking how many times you find a certain type of egg during Easter. You start by setting up your database and adding an Eggs sheet, and then adding a record for each type of egg.
Example
local mydb = db:create("egg database", {eggs = {color = "", last_found = db.Timestamp(false), found = 0}})
        db:add(mydb.eggs,
                {color = "Red"},
                {color = "Blue"},
                {color = "Green"},
                {color = "Yellow"},
                {color = "Black"}
        )
Now, you have three columns. One is a string, one a timestamp (that ends up as nil in the database), and one is a number.
You can then set up a trigger to capture from the mud the string, "You pick up a (.*) egg!", and you end up arranging to store the value of that expression in a variable called "myegg".
To increment how many we found, we will do this:
myegg = "Red" -- We will pretend a trigger set this.
        db:set(mydb.eggs.found, db:exp("found + 1"), db:eq(mydb.eggs.color, myegg))
        db:set(mydb.eggs.last_found, db.Timestamp("CURRENT_TIMESTAMP"), db:eq(mydb.eggs.color, myegg))
This will go out and set two fields in the Red egg sheet; the first is the found field, which will increment the value of that field (using the special db:exp function). The second will update the last_found field with the current time.
Once this contest is over, you may wish to reset this data but keep the database around. To do that, you may use a more broad use of db:set as such:
db:set(mydb.eggs.found, 0)
db:set(mydb.eggs.last_found, nil)

db:update

db:update(sheet reference, table)
This function updates a row in the specified sheet, but only accepts a row which has been previously obtained by db:fetch. Its primary purpose is that if you do a db:fetch, then change the value of a field or tow, you can save back that table.
Example
local mydb = db:get_database("my database")
local bob = db:fetch(mydb.friends, db:eq(mydb.friends.name, "Bob"))[1]
bob.notes = "He's a really awesome guy."
db:update(mydb.friends, bob)
This obtains a database reference, and queries the friends sheet for someone named Bob. As this returns a table array containing only one item, it assigns that one item to the local variable named bob. We then change the notes on Bob, and pass it into db:update() to save the changes back.

Date & Time Functions

A collection of functions for handling Date & Time.

datetime:parse

datetime:parse(source, format, as_epoch)
Parses the specified source string, according to the format if given, to return a representation of the date/time. If as_epoch is provided and true, the return value will be a Unix epoch — the number of seconds since 1970. This is a useful format for exchanging date/times with other systems. If as_epoch is false, then a Lua time table will be returned. Details of the time tables are provided in the Lua Manual.
Supported Format Codes
%b = Abbreviated Month Name
%B = Full Month Name
%d = Day of Month
%H = Hour (24-hour format)
%I = Hour (12-hour format, requires %p as well)
%p = AM or PM
%m = 2-digit month (01-12)
%M = 2-digit minutes (00-59)
%S = 2-digit seconds (00-59)
%y = 2-digit year (00-99), will automatically prepend 20 so 10 becomes 2010 and not 1910.
%Y = 4-digit year.

getTime

getTime(returntype, format)
returntype takes a boolean value (in Lua anything but false or nil will translate to true). If false, the function will return a table in the following format:
{ 'min': #, 'year': #, 'month': #, 'day': #, 'sec': #, 'hour': #, 'msec': # }

If true, it will return the date and time as a string using a format passed to the format arg or the default of "yyyy.MM.dd hh:mm:ss.zzz" if none is supplied:

2012.02.18 00:52:52.489

Format expressions:

h               the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
hh              the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
H               the hour without a leading zero (0 to 23, even with AM/PM display)
HH              the hour with a leading zero (00 to 23, even with AM/PM display)
m               the minute without a leading zero (0 to 59)
mm              the minute with a leading zero (00 to 59)
s               the second without a leading zero (0 to 59)
ss              the second with a leading zero (00 to 59)
z               the milliseconds without leading zeroes (0 to 999)
zzz             the milliseconds with leading zeroes (000 to 999)
AP or A         use AM/PM display. AP will be replaced by either "AM" or "PM".
ap or a         use am/pm display. ap will be replaced by either "am" or "pm".

d               the day as number without a leading zero (1 to 31)
dd              the day as number with a leading zero (01 to 31)
ddd             the abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses QDate::shortDayName().
dddd            the long localized day name (e.g. 'Monday' to 'Qt::Sunday'). Uses QDate::longDayName().
M               the month as number without a leading zero (1-12)
MM              the month as number with a leading zero (01-12)
MMM             the abbreviated localized month name (e.g. 'Jan' to 'Dec'). Uses QDate::shortMonthName().
MMMM            the long localized month name (e.g. 'January' to 'December'). Uses QDate::longMonthName().
yy              the year as two digit number (00-99)
yyyy            the year as four digit number

All other input characters will be ignored. Any sequence of characters that are enclosed in single quotes will be treated as text and not be used as an expression. Two consecutive single quotes ('') are replaced by a single single quote in the output.

Example
-- Get time as a table
@getTime()
 
-- Get time with default string
@getTime(true)
 
-- Get time without date and milliseconds
@getTime(true, "hh:mm:ss")

getTimestamp

getTimestamp( optional console_name, lineNumber )
Returns the timestamp string as it’s seen when you enable the timestamps view (blue i button bottom right).

Note Note: Available since 1.1.0-pre1

Example
--Echo the timestamp of the current line in a trigger:
echo(getTimestamp(getLineCount()))

shms

shms( seconds, bool )
Converts seconds into hours, minutes and seconds, displaying the result as a fancy echo. An optional second argument can be passed to return the values as a table.

Note Note: Will be available in 3.0

Example
--Determine the total number of seconds:
shms(65535, true)

Display Functions

A collection of functions for displaying or formatting information on the screen.

display

display(value)
This function will do it's best to show whatever you ask it (a number, string, table, function). This function can be useful for seeing what values does a table have, for example. Note that this doesn't handle recursive references and will loop infinitely at the moment (Mudlet 2.0-test4). If a value is a string, it'll be in single quotes, and if it's a number, it won't be quoted.
Example
-- ask it to display a table
display({a = "somevalue", 1,2,3})
-- or some other target
display(target)

showColors

showColors(columns)
shows the named colors currently available in Mudlet's color table. These colors are stored in color_table, in table form. The format is color_table.colorName = {r,g,b}.
See Also: bg(), fg(), cecho()
Parameters
  • columns:
Number of columns to print the color table in. Passed as an integer number.
Example
showColors(4)

The output for this is:

showColors(4)

wrapLine

wrapLine( windowName, lineNumber )
Wrap line lineNumber of mini console (window) windowName. This function will interpret \n characters, apply word wrap and display the new lines on the screen. This function may be necessary if you use deleteLine() and thus erase the entire current line in the buffer, but you want to do some further echo() calls after calling deleteLine(). You will then need to re-wrap the last line of the buffer to actually see what you have echoed and get you \n interpreted as newline characters properly. Using this function is no good programming practice and should be avoided. There are better ways of handling situations where you would call deleteLine() and echo afterwards.
Example
--This will effectively have the same result as a call to deleteLine() but the buffer line will not be entirely removed. 
--Consequently, further calls to echo() etc. sort of functions are possible without using wrapLine() unnecessarily.
 
selectString(line,1);
replace("");

File System Functions

A collection of functions for interacting with the file system.

io.exists

io.exists()
Checks to see if a given file or folder exists.
If it exists, it’ll return the Lua true boolean value, otherwise false.
Note: Behavior varies based on the user's operating system. Windows requires a specific file, while Linux will accept directories.
See lfs.attributes() for a cross-platform solution.
Example
-- This example works on Linux only
if io.exists("/home/vadi/Desktop") then
  echo("This folder exists!")
else
  echo("This folder doesn't exist.")
end
 
-- This example will work on both Windows and Linux.
if io.exists("/home/vadi/Desktop/file.tx") then
  echo("This file exists!")
else
  echo("This file doesn't exist.")
end

lfs.attributes

lfs.attributes(path)
Returns a table with detailed information regarding a file or directory, or nil if path is invalid / file or folder does not exist.
Example
fileInfo = lfs.attributes("/path/to/file_or_directory")
if fileInfo then
    if fileInfo.mode == "directory" then
        echo("Path points to a directory.")
    elseif fileInfo.mode == "file" then
        echo("Path points to a file.")
    else
        echo("Path points to: "..fileInfo.mode)
    end
    display(fileInfo) -- to see the detailed information
else
    echo("The path is invalid (file/directory doesn't exist)")
end

Mapper Functions

These are functions that are to be used with the Mudlet Mapper. The mapper is designed to be MUD-generic - it only provides the display and pathway calculations, to be used in Lua scripts that are tailored to the MUD you're playing. For a collection of pre-made scripts and general mapper talk, visit the mapper section of the forums.

To register a script as a mapping one with Mudlet (so Mudlet knows the profile has one and won't bother the user when they open the map), please do this in your script:

mudlet = mudlet or {}; mudlet.mapper_script = true

addAreaName

areaID = addAreaName(areaName)
Adds a new area name and returns the new area ID for the new name. If the name already exists, -1 is returned.
See also: deleteArea(), addRoom()
Example
local newID = addAreaName("My house")
 
if newID == -1 then echo("That area name is already taken :(\n")
else echo("Created new area with the ID of "..newid..".\n") end

addMapEvent

addMapEvent(uniquename, event name, parent, display name, arguments)
Adds a new entry to an existing mapper right-click entry. You can add one with addMapMenu. If there is no display name, it will default to the unique name (which otherwise isn't shown and is just used to differentiate this entry from others). event name is the Mudlet event that will be called when this is clicked on, and arguments will be passed to the handler function.
See also: addMapMenu(), removeMapEvent(), getMapEvents()
Example
addMapEvent("room a", "onFavorite") -- will make a label "room a" on the map menu's right click that calls onFavorite
 
addMapEvent("room b", "onFavorite", "Favorites", "Special Room!", 12345, "arg1", "arg2", "argn")

The last line will make a label "Special Room!" under the "Favorites" menu that on clicking will send all the arguments.

addMapMenu

addMapEvent(uniquename, parent, display name)
Adds a new submenu to the right-click menu that opens when you right-click on the mapper. You can then add more submenus to it, or add entries with addMapEvent().
See also: addMapEvent(), removeMapEvent(), getMapEvents()
Example
addMapMenu("Favorites") -- will create a menu, favorites
 
addMapMenu("Favorites1234343", "Favorites", "Favorites")

The last line will create a submenu with the unique id Favorites123.. under Favorites with the display name of Favorites.

addRoom

addRoom(roomID)
Creates a new room with the given ID, returns true if the room was successfully created.

Note Note: If you're not using incremental room IDs but room IDs stitched together from other factors or in-game hashes for room IDs - and your room IDs are starting off at 250+million numbers, you need to look into incrementally creating Mudlets room IDs with createRoomID() and associating your room IDs with Mudlets via setRoomIDbyHash() and getRoomIDbyHash(). The reason being is that Mudlet's A* pathfinding implementation from boost cannot deal with extremely large room IDs because the resulting matrices it creates for pathfinding are enormously huge.

See also: createRoomID()
Example
local newroomid = createRoomID()
addRoom(newroomid)

addSpecialExit

addSpecialExit(roomIDFrom, roomIDTo, command)
Creates a one-way from one room to another, that will use the given command for going through them.
See also: clearSpecialExits()
Example
-- sample alias pattern: ^spe (\d+) (.*?)$
-- mmp.currentroom is your current room ID in this example
addSpecialExit(mmp.currentroom,tonumber(matches[2]), matches[3])
echo("\n SPECIAL EXIT ADDED TO ROOMID:"..matches[2]..", Command:"..matches[3])
centerview(mmp.currentroom)

centerview

centerview (roomID)
Centers the map view onto the given room ID. The map must be open to see this take effect. This function can also be used to see the map of an area if you know the number of a room there and the area and room are mapped.

clearRoomUserData

clearRoomUserData(roomID)
Clears all user data from a given room.
See also: setRoomUserData()
Example
clearRoomUserData(341)

clearSpecialExits

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

connectExitStub

connectExitStub(fromID, direction or toID[, optional direction])
Connects existing rooms with matching exit stubs. If you only give it a roomID and a direction, it'll work out which room should be linked to it that has an appropriate opposite exit stub and is located in the right direction. You can also just specify from and to room IDs, and it'll smartly use the right direction to link in. Lastly, you can specify all three arguments - fromID, toID and the direction (in that order) if you'd like to be explicit, or use setExit() for the same effect.
Parameters
  • fromID:
Room ID to set the exit stub in.
  • direction or toID:
You can either specify the direction to link the room in, or a specific room ID. Direction is specified as a # that the exit stub points at, or you can also use exitmap["direction"] instead. If you specify the room
  • toID:
Optional - the room ID to link this room to. If you don't specify it, the mapper will work out which room should be logically linked.
See also: getExitStubs()
Example
-- try and connect all stubs that are in a room
local stubs = getExitStubs(roomID)
  if stubs then
    for i,v in pairs(stubs) do
    connectExitStub(roomID, v)
  end
end

createMapLabel

labelID = createMapLabel(areaID, text, posx, posy, posz, fgRed, fgGreen, fgBlue, bgRed, bgGreen, bgBlue, zoom, fontSize, showOnTop, noScaling)
Creates a text label on the map at given coordinates, with the given background and foreground colors. It can go above or below the rooms, scale with zoom or stay a static size. It returns a label ID that you can use later for deleting it.
The coordinates 0,0 are in the middle of the map, and are in sync with the room coordinates - so using the x,y values of getRoomCoordinates() will place the label near that room.
See also: deleteMapLabel
Example
-- the first 50 is some area is, the next three 0,0,0 are coordinates - middle of the area
-- 255,0,0 would be the foreground in RGB, 23,0,0 would be the background RGB
-- zoom is only relevant when when you're using a label of a static size, so we use 0
-- and we use a font size of 20 for our label, which is a small medium compared to the map
local labelid = createMapLabel( 50, "my map label", 0,0,0, 255,0,0, 23,0,0, 0,20)

createMapImageLabel

labelID = createMapImageLabel(areaID, filePath, posx, posy, posz, width, height, zoom, showOnTop)
Creates an image label on the map at the given coordinates, with the given dimensions and zoom. You might find the default room and image size correlation to be too big - try reducing the width and height of the image then, while also zooming in the same amount.
The coordinates 0,0 are in the middle of the map, and are in sync with the room coordinates - so using the x,y values of getRoomCoordinates() will place the label near that room.
See also: deleteMapLabel
Example
-- 138 is our pretend area ID
-- next, inside [[]]'s, is the exact location of our image
-- 0,0,0 are the x,y,z coordinates - so this will place it in the middle of the map
-- 482 is the width of the image - we divide it by 100 to scale it down, and then we'll zoom it by 100 - making the image take up about 4 rooms in width then
-- 555 is the original width of the image
-- 100 is how much we zoom it by, 1 would be no zoom
-- and lastly, false to make it go below our rooms
createMapImageLabel(138, [[/home/vadi/Pictures/You only see what shown.png]], 0,0,0, 482/100, 555/100, 100, false)

createMapper

createMapper(x, y, width, height)
Creates a miniconsole window for the mapper to render in, the with the given dimensions. You can only create one mapper at a time.
Example
createMapper(0,0,300,300) -- creates a 300x300 mapper top-right of Mudlet
setBorderLeft(305) -- adds a border so text doesn't underlap the mapper display

createRoomID

usableId = createRoomID()
Returns the lowest possible room ID you can use for creating a new room. If there are gaps in room IDs your map uses it, this function will go through the gaps first before creating higher IDs.
See also: addRoom()

deleteArea

deleteArea(areaID)
Deletes the given area, permanently. This will also delete all rooms in it!
See also: addAreaName()
Example
deleteArea(23)

deleteMapLabel

deleteMapLabel(areaID, labelID)
Deletes a map label from a specfic area.
See also: createMapLabel()
Example
deleteMapLabel(50, 1)

deleteRoom

deleteRoom(roomID)
Deletes an individual room, and unlinks all exits leading to and from it.
Example
deleteRoom(335)

getAreaRooms

getAreaRooms(area id)
Returns an indexed table with all rooms IDs for a given area ID (room IDs are values), or nil if no such area exists.

Note Note: On Mudlet versions prior to the 2.0 final release, this function would raise an error.

Example
-- using the sample findAreaID() function defined in the getAreaTable() example, 
-- we'll define a function that echo's us a nice list of all rooms in an area with their ID
function echoRoomList(areaname)
  local id, msg = findAreaID(areaname)
  if id then
    local roomlist, endresult = getAreaRooms(id), {}
 
    -- obtain a room list for each of the room IDs we got
    for _, id in ipairs(roomlist) do
      endresult[id] = getRoomName(id)
    end
 
    -- now display something half-decent looking
    cecho(string.format(
      "List of all rooms in %s (%d):\n", msg, table.size(endresult)))
 
    for roomid, roomname in pairs(endresult) do
      cecho(string.format(
        "%6s: %s\n", roomid, roomname))
    end
  elseif not id and msg then
    echo("ID not found; " .. msg)
  else
    echo("No areas matched the query.")
  end
end

getAreaTable

getAreaTable()
Returns a key(area name)-value(area id) table with all known areas and their IDs. There is an area with the name of and an ID of 0 included in it, you should ignore that.
See also: getAreaTableSwap()
Example
-- example function that returns the area ID for a given area
 
function findAreaID(areaname)
  local list = getAreaTable()
 
  -- iterate over the list of areas, matching them with substring match. 
  -- if we get match a single area, then return it's ID, otherwise return
  -- 'false' and a message that there are than one are matches
  local returnid, fullareaname
  for area, id in pairs(list) do
    if area:find(areaname, 1, true) then
      if returnid then return false, "more than one area matches" end
      returnid = id; fullareaname = area
    end
  end
 
  return returnid, fullareaname
end
 
-- sample use:
local id, msg = findAreaID("blahblah")
if id then
  echo("Found a matching ID: " .. id")
elseif not id and msg then
  echo("ID not found; " .. msg)
else
  echo("No areas matched the query.")
end

getAreaTableSwap

getAreaTableSwap()
Returns a key(area id)-value(area name) table with all known areas and their IDs. Unlike getAreaTable which won't show you all areas with the same name by different IDs, this function will. There is an area with the name of and an ID of 0 included in it, you should ignore that.

getCustomEnvColorTable

envcolors = getCustomEnvColorTable()
Returns a table with customized environments, where the key is the environment ID and the value is a indexed table of rgb values.
Example
{
  envid1 = {r,g,b},
  envid2 = {r,g,b}
}

getDoors

doors = getDoors(roomID)
Returns a key-value table with the cardinal direction as the key and the door value as a number. If there are no doors in a room, it returns an empty table.
Parameters
  • roomID:
Room ID to check for doors in.
See also: setDoor()
Example
-- an example that displays possible doors in room 2334
local doors = getDoors(2334)
 
if not next(doors) then cecho("\nThere aren't any doors in room 2334.") return end
 
local door_status = {"open", "closed", "locked"}
 
for direction, door in pairs(doors) do
  cecho("\nThere's a door leading in "..direction.." that is "..door_status[door]..".")
end

getExitStubs

stubs = getExitStubs(roomid)
Returns an indexed table of the direction #'s that have an exit stub marked in them. You can use this information to connect earlier-made exit stubs between rooms when mapping.
Example
-- show the exit stubs in room 6 as numbers
local stubs = getExitStubs(6)
for i = 0, #stubs do print(stubs[i]) end
 
-- show the exit stubs in room 6 as numbers as direction names, using exitmap from http://wiki.mudlet.org/w/Mapping_script#Translating_directions
local stubs = getExitStubs(6)
for i = 0, #stubs do print(exitmap[stubs[i]]) end

getExitWeights

weights = getExitWeights(roomid)
Returns a key-value table of the exit weights that a room has, with the direction or special exit as a key and the value as the exit weight. If a weight for a direction wasn't yet set, it won't be listed.
Parameters
  • roomid:
Room ID to view the exit weights in.
See also: setExitWeight()

getMapLabel

labelinfo = getMapLabels(areaID, labelID)
Returns a key-value table describing that particular label in an area. Keys it contains are the X, Y, Z coordinates, Height and Width, and the Text it contains. If the label is an image label, then Text will be set to the no text string.
Example
lua getMapLabels(1658987)
table {
  1: 'no text'
  0: 'test'
}
 
lua getMapLabel(1658987, 0)
table {
  'Y': -2
  'X': -8
  'Z': 11
  'Height': 3.9669418334961
  'Text': 'test'
  'Width': 8.6776866912842
}
 
lua getMapLabel(1658987, 1)
table {
  'Y': 8
  'X': -15
  'Z': 11
  'Height': 7.2520666122437
  'Text': 'no text'
  'Width': 11.21900844574
}


getMapLabels

arealabels = getMapLabels(areaID)
Returns an indexed table (that starts indexing from 0) of all of the labels in the area, plus their label text. You can use the label id to deleteMapLabel() it.
Example
display(getMapLabels(43))
table {
  0: ''
  1: 'Waterways'
}
 
deleteMapLabel(43, 0)
display(getMapLabels(43))
table {
  1: 'Waterways'
}

getPath

getPath(roomID from, roomID to)
Returns a boolean true/false if a path between two room IDs is possible. If it is, the global speedWalkPath table is set to all of the directions that have to be taken to get there, and the global speedWalkDir table is set to all of the roomIDs you'll encounter on the way.
Example
-- check if we can go to a room - if yes, go to it
if getPath(34,155) then
  gotoRoom(155)
else
  echo("\nCan't go there!")
end

getRoomArea

areaID = getRoomArea(roomID)
Returns the area ID of a given room ID. To get the area name, you can check the area ID against the data given by getAreaTable() function, or use the getRoomAreaName() function.

Note Note: If the room ID does not exist, this function will raise an error.

Example
display("Area ID of room #100 is: "..getRoomArea(100))
 
display("Area name for room #100 is: "..getRoomAreaName(getRoomArea(100)))

getRoomAreaName

areaname = getRoomAreaName(areaID)
Returns the area name for a given area id.
Example
echo(string.format("room id #455 is in %s.", getRoomAreaName(getRoomArea(455))))

getRoomCoordinates

x,y,z = getRoomCoordinates(room ID)
Returns the room coordinates of the given room ID.
Example
local x,y,z = getRoomCoordinates(roomID)
echo("Room Coordinates for "..roomID..":")
echo("\n     X:"..x)
echo("\n     Y:"..y)
echo("\n     Z:"..z)

getRoomEnv

envID = getRoomEnv(roomID)
Returns the environment ID of a room. The mapper does not store environment names, so you'd need to keep track of which ID is what name yourself.
Example
funtion checkID(id)
  echo(strinf.format("The env ID of room #%d is %d.\n", id, getRoomEnv(id)))
end

getRoomExits

getRoomExits (roomID)
Returns the currently known non-special exits for a room in an key-index form: exit = exitroomid.
See also: getSpecialExits()
Example
table {
  'northwest': 80
  'east': 78
}

Here's a practical example that queries the rooms around you and searched for one of the water environments (the number would depend on how it was mapped):

local exits = getRoomExits(mycurrentroomid)
for direction,num in pairs(exits) do
  local env_num = getRoomEnv(num)
  if env_num == 22 or env_num == 20 or env_num == 30 then
    print("There's water to the "..direction.."!")
  end
end

getRoomIDbyHash

roomID = getRoomIDbyHash(hash)
Returns a room ID that is associated with a given hash in the mapper. This is primarily for MUDs that make use of hashes instead of room IDs (like Avalon.de MUD). -1 is returned if no room ID matches the hash.
Example
-- example taken from http://forums.mudlet.org/viewtopic.php?f=13&t=2177
_id1 = getRoomIDbyHash( "5dfe55b0c8d769e865fd85ba63127fbc" );
if _id1 == -1 then 
  _id1 = createRoomID()
  setRoomIDbyHash( _id1, "5dfe55b0c8d769e865fd85ba63127fbc" )
  addRoom( _id )
  setRoomCoordinates( _id1, 0, 0, -1 )
end

getRoomName

roomName = getRoomName(roomID)
Returns the room name for a given room id.
Example
echo(string.format("The name of the room id #455 is %s.", getRoomName(455))

getRooms

rooms = getRooms()
Returns the list of all rooms in the map in the whole map in roomid - room name format.
Example
-- simple, raw viewer for rooms in the world
display(getRooms())

getRoomsByPosition

getRoomsByPosition(areaID, x,y,z)
Returns an indexed table of all rooms at the given coordinates in the given area, or an empty one if there are none. This function can be useful for checking if a room exists at certain coordinates, or whenever you have rooms overlapping.
Example
-- sample alias to determine a room nearby, given a relative direction from the current room
 
local otherroom
if matches[2] == "" then
  local w = matches[3]
  local ox, oy, oz, x,y,z = getRoomCoordinates(mmp.currentroom)
  local has = table.contains
  if has({"west", "left", "w", "l"}, w) then
    x = (x or ox) - 1; y = (y or oy); z = (z or oz)
  elseif has({"east", "right", "e", "r"}, w) then
    x = (x or ox) + 1; y = (y or oy); z = (z or oz)
  elseif has({"north", "top", "n", "t"}, w) then
    x = (x or ox); y = (y or oy) + 1; z = (z or oz)
  elseif has({"south", "bottom", "s", "b"}, w) then
    x = (x or ox); y = (y or oy) - 1; z = (z or oz)
  elseif has({"northwest", "topleft", "nw", "tl"}, w) then
    x = (x or ox) - 1; y = (y or oy) + 1; z = (z or oz)
  elseif has({"northeast", "topright", "ne", "tr"}, w) then
    x = (x or ox) + 1; y = (y or oy) + 1; z = (z or oz)
  elseif has({"southeast", "bottomright", "se", "br"}, w) then
    x = (x or ox) + 1; y = (y or oy) - 1; z = (z or oz)
  elseif has({"southwest", "bottomleft", "sw", "bl"}, w) then
    x = (x or ox) - 1; y = (y or oy) - 1; z = (z or oz)
  elseif has({"up", "u"}, w) then
    x = (x or ox); y = (y or oy); z = (z or oz) + 1
  elseif has({"down", "d"}, w) then
    x = (x or ox); y = (y or oy); z = (z or oz) - 1
  end
 
  local carea = getRoomArea(mmp.currentroom)
  if not carea then mmp.echo("Don't know what area are we in.") return end
 
  otherroom = select(2, next(getRoomsByPosition(carea,x,y,z)))
 
  if not otherroom then
    mmp.echo("There isn't a room to the "..w.." that I see - try with an exact room id.") return
  else
    mmp.echo("The room "..w.." of us has an ID of "..otherroom)
  end

getRoomUserData

data = getRoomUserData(roomID, key (as a string))
Returns the user data stored at a given room with a given key, or "" if none is stored. Use setRoomUserData() function for setting the user data.
Example
display(getRoomUserData(341, "visitcount"))

getRoomWeight

room weight = getRoomWeight(roomID)
Returns the weight of a room. By default, all new rooms have a weight of 1.
See also: setRoomWeight()
Example
display("Original weight of room 541: "..getRoomWeight(541)
setRoomWeight(541, 3)
display("New weight of room 541: "..getRoomWeight(541)

getSpecialExits

exits = getSpecialExits(roomID)
Returns a roomid - command table of all special exits in the room. If there are no special exits in the room, the table returned will be empty.
See also: getRoomExits()
Example
getSpecialExits(1337)
 
-- results in:
--[[
table {
  12106: 'faiglom nexus'
}
]]

getSpecialExitsSwap

exits = getSpecialExitsSwap(roomID)
Very similar to getSpecialExits() function, but returns the rooms in the command - roomid style.

gotoRoom

gotoRoom (roomID)
Speedwalks you to the given room from your current room if it is able and knows the way. You must turn the map on for this to work, else it will return "(mapper): Don't know how to get there from here :(".

hasExitLock

status = hasExitLock(roomID, direction)
Returns true or false depending on whenever a given exit leading out from a room is locked. direction right now is a number that corresponds to the direction:

 exitmap = {
   n = 1,
   north = 1,
   ne = 2,
   northeast = 2,
   nw = 3,
   northwest = 3,
   e = 4,
   east = 4,
   w = 5,
   west = 5,
   s = 6,
   south = 6,
   se = 7,
   southeast = 7,
   sw = 8,
   southwest = 8,
   u = 9,
   up = 9,
   d = 10,
   down = 10,
   ["in"] = 11,
   out = 12
 }

Example
-- check if the east exit of room 1201 is locked
display(hasExitLock(1201, 4))
See also: lockExit()

hasSpecialExitLock

status = hasSpecialExitLock(from roomID, to roomID, command)
Returns true or false depending on whenever a given exit leading out from a room is locked. command is the action to take to get through the gate.
-- lock a special exit from 17463 to 7814 that uses the 'enter feather' command
lockSpecialExit(17463, 7814, 'enter feather', true)
 
-- see if it is locked: it will say 'true', it is
display(hasSpecialExitLock(17463, 7814, 'enter feather'))

highlightRoom

highlightRoom( id, r1,g1,b1,r2,g2,b2, radius, alpha1, alpha2)
Highlights a room with the given color, which will override it's environment color. If you use two different colors, then there'll be a shading from the center going outwards that changes into the other color. highlightRadius is the radius for the highlight circle - if you don't want rooms beside each other to over lap, use 1 as the radius. alphaColor1 and alphaColor2 are transparency values from 0 (completely transparent) to 255 (not transparent at all).
See also: unHighlightRoom()

Note Note: Available since Mudlet 2.0 final release

-- color room #351 red to blue
local r,g,b = unpack(color_table.red)
local br,bg,bb = unpack(color_table.blue)
highlightRoom(351, r,g,b,br,bg,bb, 1, 255, 255)

exportAreaImage

exportAreaImage(areaID)
Exports the area as an image into your profile's directory.
Example
-- save the area with ID 1 as a map
exportAreaImage(1)

loadMap

boolean = loadMap(file location)
Loads the map file from a given location. The map file must be in Mudlet's format (not XML or any other) - saved with saveMap().
Returns a boolean for whenever the loading succeeded. Note that the mapper must be open, or this will fail.
See also: saveMap()
  loadMap("/home/user/Desktop/Mudlet Map.dat")

lockExit

lockExit(roomID, direction, lock = true/false)
Locks a given exit from a room (which means that unless all exits in the incoming room are locked, it'll still be accessible). Direction at the moment is only set as a number, and here's a listing of them:

 exitmap = {
   n = 1,
   north = 1,
   ne = 2,
   northeast = 2,
   nw = 3,
   northwest = 3,
   e = 4,
   east = 4,
   w = 5,
   west = 5,
   s = 6,
   south = 6,
   se = 7,
   southeast = 7,
   sw = 8,
   southwest = 8,
   u = 9,
   up = 9,
   d = 10,
   down = 10,
   ["in"] = 11,
   out = 12
 }

Example
-- lock the east exit of room 1201 so we never path through it
lockExit(1201, 4, true)
See also: hasExitLock()

lockRoom

lockRoom (roomID, lock = true/false)
Locks a given room id from future speed walks (thus the mapper will never path through that room).
See also: roomLocked()
Example
lockRoom(1, true) -- locks a room if from being walked through when speedwalking.
lockRoom(1, false) -- unlocks the room, adding it back to possible rooms that can be walked through.

lockSpecialExit

lockSpecialExit (from roomID, to roomID, special exit command, lock = true/false)
Locks a given special exit, leading from one specific room to another that uses a certain command from future speed walks (thus the mapper will never path through that special exit).
See also: hasSpecialExitLock(), lockExit(), lockRoom()
Example
lockSpecialExit(1,2,'enter gate', true) -- locks the special exit that does 'enter gate' to get from room 1 to room 2
lockSpecialExit(1,2,'enter gate', false) -- unlocks the said exit

removeMapEvent

removeMapEvent (event name)
Removes the given menu entry from a mappers right-click menu. You can add custom ones with addMapEvent().
See also: addMapEvent(), addMapMenu(), getMapEvents()
Example
addMapEvent("room a", "onFavorite") -- add one to the general menu
removeMapEvent("room a") -- removes the said menu

roomExists

roomExists(roomID)
Returns a boolean true/false depending if the room with that ID exists (is created) or not.

roomLocked

locked = roomLocked(roomID)
Returns true or false whenever a given room is locked.
See also: lockRoom()
Example
echo(string.format("Is room #4545 locked? %s.", roomLocked(4545) and "Yep" or "Nope"))

saveMap

saveMap(location)
Saves the map to a given location, and returns true on success. The location folder needs to be already created for save to work.
See also: loadMap()
Example
local savedok = saveMap(getMudletHomeDir().."/my fancy map.dat")
if not savedok then
  echo("Couldn't save :(\n")
else
  echo("Saved fine!\n")
end

searchRoom

searchRoom (room name / room number)
Searches for rooms that match (by case-insensitive, substring match) the given room name. It returns a key-value table in form of roomid = roomname.
If you pass it a number instead of a string, it'll act like getRoomName() and return you the room name.
Example
display(searchRoom("master"))
 
--[[ would result in:
table {
  17463: 'in the branches of the Master Ravenwood'
  3652: 'master bedroom'
  10361: 'Hall of Cultural Masterpieces'
  6324: 'Exhibit of the Techniques of the Master Artisans'
  5340: 'office of the Guildmaster'
  (...)
  2004: 'office of the guildmaster'
  14457: 'the Master Gear'
  1337: 'before the Master Ravenwood Tree'
}
]]

If no rooms are found, then an empty table is returned.

setAreaName

setAreaName(areaID, newName)
Names, or renames an existing area to the new name. The area must be created first with addAreaName().
See also: deleteArea(), addAreaName()
Example
setAreaName(2, "My city")

setCustomEnvColor

setCustomEnvColor(environmentID, r,g,b,a)
Creates, or overrides an already created custom color definition for a given environment ID. Note that this will not work on the default environment colors - those are adjustable by the user in the preferences. You can however create your own environment and use a custom color definition for it.

Note Note: Numbers 1-16 and 257-272 are reserved by Mudlet. 257-272 are the default colors the user can adjust in mapper settings, so feel free to use them if you'd like - but don't overwrite them with this function.

Example
setRoomEnv(571, 200) -- change the room's environment ID to something arbitrary, like 200
local r,g,b = unpack(color_table.blue)
setCustomEnvColor(200, r,g,b, 255) -- set the color of environmentID 200 to blue

setDoor

setDoor(roomID, exitCommand, doorStatus)
Creates or deletes a door in a room. Doors are purely visual - they don't affect pathfinding. You can use the information to change to adjust your speedwalking path based on the door information in a room, though.
Parameters
  • roomID:
Room ID to to create the door in.
  • exitCommand:
The cardinal direction for the door is in - it can be one of the following: e,s,w,n,ne,se,sw,ne. {Plans are afoot to add support for doors on the other normal exits: up,down,in,out and also on special exits though more work will be needed for them to be shown in the mapper.}
  • doorStatus:
The door status as a number - 0 means remove door, 1 means open door (will draw a green square on exit), 2 means closed door (yellow square) and 3 means locked door (red square).
See also: getDoors()
Example
-- make a door on the east exit of room 4234 that is currently open
setDoor(4234, 'e', 1)
 
-- remove a door from room 923 that points north
setDoor(923, 'n', 0)

setExit

setExit(from roomID, to roomID, direction)
Creates a one-way exit from one room to another using a standard direction - which can be either one of n, ne, nw, e, w, s, se, sw, u, d, in, out, or a number which represents a direction. If there was an exit stub in that direction already, then it will be automatically deleted for you.
Returns false if the exit creation didn't work.
Example
-- alias pattern: ^exit (\d+) (\d+) (\w+)$
-- so exit 1 2 5 will make an exit from room 1 to room 2 via north
 
if setExit(tonumber(matches[2]), tonumber(matches[3]), matches[4]) then
  echo("\nExit set to room:"..matches[3].." from "..matches[2]..", direction:"..string.upper(matches[3]))
else
  echo("Failed to set the exit.\n")
end

This function can also delete exits from a room if you use it like so:

setExit(from roomID, -1, direction)

- which will delete an outgoing exit in the specified direction from a room.

setExitStub

setExitStub(roomID, direction, set/unset)

Creates or removes an exit stub from a room in a given directions. You can use exit stubs later on to connect rooms that you're sure of are together. Exit stubs are also shown visually on the map, so the mapper can easily tell which rooms need finishing.

Parameters
  • roomID:
The room to place an exit stub in, as a number.
  • direction:
The direction the exit stub should lead in, as a number (to use a direction name, see exitmap)
  • set/unset:
A boolean to create or delete the exit stub.
See also: getExitStubs(), connectExitStub()
Example

Create an exit stub to the south from room 6:

setExitStub(8, 6, true)

.. or using an exitmap (see Mapping_script#Translating_directions):

setExitStub(8, exitmap.s, true)

How to delete all exit stubs in a room:

for i,v in pairs(getExitStubs(roomID)) do
  setExitStub(roomID, v,false)
end

setExitWeight

setExitWeight(roomID, exitCommand, weight)
Gives an exit a weight, which makes it less likely to be chosen for pathfinding. All exits have a weight of 0 by default, which you can increase. Exit weights are set one-way on an exit - if you'd like the weight to be applied both ways, set it from the reverse room and direction as well.
Parameters
  • roomID:
Room ID to to set the weight in.
  • exitCommand:
The the direction for the exit is in - it can be one of the following: e,s,w,n,ne,se,sw,ne,up,down,in,out, or if it's a special exit, the special exit command.
  • weight:
Exit weight - by default, all exits have a weight of 0. Increasing the weight will make the room less likely be chosen for pathfinding.
See also: getExitWeights()

setGridMode

setGridMode(areaID, true/false)
Enables grid/wilderness view mode for an area - this will cause the rooms to lose their visible exit connections, like you'd see on compressed ASCII maps, both in 2D and 3D view mode.
Example
setGridMode(55, true) -- set area with ID 55 to be in grid mode

setMapZoom

setMapZoom(zoom)
Zooms the map in to a given zoom level. 1 is the closest you can get, and anything higher than that zooms the map out. Call centerview() after you set the zoom to refresh the map.
Example
setMapZoom(10) -- zoom to a somewhat acceptable level, a bit big but easily visible connections

setModulePriority

setModulePriority(module name, priority #)
Sets the module priority on a given module as a number - the module priority determines the order modules are loaded in, which can be helpful if you have ones dependent on each other. This can also be set from the module manager window.
See also: getModulePriority()
setModulePriority("mudlet-mapper", 1)

setRoomArea

setRoomArea(roomID, newAreaID)
Assigns the given room to a new area. This will have the room be visually moved into the area as well.

setRoomChar

setRoomChar(roomID, character)
Designed for an area in grid mode, this will set a single character to be on a room. You can use "_" to clear it.
Example
setRoomChar(431, "#")
 
setRoomChar(123. "$")

setRoomCoordinates

setRoomCoordinates(roomID, x, y, z)
Sets the given room ID to be at the following coordinates visually on the map, where z is the up/down level.

Note Note: 0,0,0 is the center of the map.

Example
-- alias pattern: ^set rc (-?\d+) (-?\d+) (-?\d+)$
local x,y,z = getRoomCoordinates(previousRoomID)
local dir = matches[2]
 
if dir == "n" then
  y = y+1
elseif dir == "ne" then
  y = y+1
  x = x+1
elseif dir == "e" then
  x = x+1
elseif dir == "se" then
  y = y-1
  x = x+1
elseif dir == "s" then
  y = y-1
elseif dir == "sw" then
  y = y-1
  x = x-1
elseif dir == "w" then
  x = x-1
elseif dir == "nw" then
  y = y+1
  x = x-1
elseif dir == "u" or dir == "up" then
  z = z+1
elseif dir == "down" then
  z = z-1
end
setRoomCoordinates(roomID,x,y,z)
centerview(roomID)
You can make them relative as well:
-- alias pattern: ^src (\w+)$
 
local x,y,z = getRoomCoordinates(previousRoomID)
local dir = matches[2]
 
if dir == "n" then
  y = y+1
elseif dir == "ne" then
  y = y+1
  x = x+1
elseif dir == "e" then
  x = x+1
elseif dir == "se" then
  y = y-1
  x = x+1
elseif dir == "s" then
  y = y-1
elseif dir == "sw" then
  y = y-1
  x = x-1
elseif dir == "w" then
  x = x-1
elseif dir == "nw" then
  y = y+1
  x = x-1
elseif dir == "u" or dir == "up" then
  z = z+1
elseif dir == "down" then
  z = z-1
end
setRoomCoordinates(roomID,x,y,z)
centerview(roomID)

setRoomEnv

setRoomEnv(roomID, newEnvID)
Sets the given room to a new environment ID. You don't have to use any functions to create it - can just set it right away.
Example
setRoomEnv(551, 34) -- set room with the ID of 551 to the environment ID 34

setRoomIDbyHash

setRoomIDbyHash(roomID, hash)
Sets the hash to be associated with the given roomID. See also getRoomIDbyHash().

setRoomName

setRoomName(roomID, newName)
Renames an existing room to a new name.
Example
setRoomName(534, "That evil room I shouldn't visit again.")
lockRoom(534, true) -- and lock it just to be safe

setRoomUserData

setRoomUserData(roomID, key (as a string), value (as a string))
Stores information about a room under a given key. Similar to Lua's key-value tables, except only strings may be used here. One advantage of using userdata is that it's stored within the map file itself - so sharing the map with someone else will pass on the user data. You can have as many keys as you'd like.
Returns true if successfully set.
See also: clearRoomUserData()


Example
-- can use it to store room descriptions...
setRoomUserData(341, "description", "This is a plain-looking room.")
 
-- or whenever it's outdoors or not...
setRoomUserData(341, "ourdoors", "true")
 
-- how how many times we visited that room
local visited = getRoomUserData(341, "visitcount")
visited = (tonumber(visited) or 0) + 1
setRoomUserData(341, "visitcount", tostring(visited))
 
-- can even store tables in it, using the built-in yajl.to_string function
setRoomUserData(341, "some table", yajl.to_string({name = "bub", age = 23}))
display("The denizens name is: "..yajl.to_value(getRoomUserData(341, "some table")).name)

setRoomWeight

setRoomWeight(roomID, weight)
Sets a weight to the given roomID. By default, all rooms have a weight of 1 - the higher the weight is, the more likely the room is to be avoided for pathfinding. For example, if travelling across water rooms takes more time than land ones - then you'd want to assign a weight to all water rooms, so they'd be avoided if there are possible land pathways.

Note Note: The minimum allowed room weight is 1.

To completely avoid a room, make use of lockRoom().
See also: getRoomWeight()


Example
setRoomWeight(1532, 3) -- avoid using this room if possible, but don't completely ignore it

speedwalk

speedwalk(dirString, backwards, delay)
A speedwalking function will work on cardinal+ordinal directions (n, ne, e, etc.) as well as u (for up), d (for down), in and out. It can be called to execute all directions directly after each other, without delay, or with a custom delay, depending on how fast your mud allows you to walk. It can also be called with a switch to make the function reverse the whole path and lead you backwards.
Call the function by doing: speedwalk("YourDirectionsString", true/false, delaytime)
The delaytime parameter will set a delay between each move (set it to 0.5 if you want the script to move every half second, for instance). It is optional: If you don't indicate it, the script will send all direction commands right after each other. (If you want to indicate a delay, you -have- explicitly indicate true or false for the reverse flag.)
The "YourDirectionsString" contains your list of directions and steps (e.g.: "2n, 3w, u, 5ne"). Numbers indicate the number of steps you want it to walk in the direction specified after it. The directions must be separated by anything other than a letter that can appear in a direction itself. (I.e. you can separate with a comma, spaces, the letter x, etc. and any such combinations, but you cannot separate by the letter "e", or write two directions right next to each other with nothing in-between, such as "wn". If you write a number before every direction, you don't need any further separator. E.g. it's perfectly acceptable to write "3w1ne2e".) The function is not case-sensitive.
If your Mud only has cardinal directions (n,e,s,w and possibly u,d) and you wish to be able to write directions right next to each other like "enu2s3wdu", you'll have to change the pattern slightly. (See the link at the beginning of my post for something like that.)
Likewise, if your Mud has any other directions than n, ne, e, se, s, sw, w, nw, u, d, in, out, the function must be adapted to that.
Example
speedwalk("16d1se1u")
-- Will walk 16 times down, once southeast, once up. All in immediate succession.
 
speedwalk("2ne,3e,2n,e")
-- Will walk twice northeast, thrice east, twice north, once east. All in immediate succession.
 
speedwalk("IN N 3W 2U W", false, 0.5)
-- Will walk in, north, thrice west, twice up, west, with half a second delay between every move.
 
speedwalk("5sw - 3s - 2n - w", true)
-- Will walk backwards: east, twice south, thrice, north, five times northeast. All in immediate succession.
 
speedwalk("3w, 2ne, w, u", true, 1.25)
-- Will walk backwards: down, east, twice southwest, thrice east, with 1.25 seconds delay between every move.

Note Note: The probably most logical usage of this would be to put it in an alias. For example, have the pattern ^/(.+)$ execute: speedwalk(matches[2], false, 0.7) And have ^//(.+)$ execute: speedwalk(matches[2], true, 0.7)

Or make aliases like: ^banktohome$ to execute
speedwalk("2ne,e,ne,e,3u,in", true, 0.5)

unHighlightRoom

unHighlightRoom(roomID)
Unhighlights a room if it was previously highlighted and restores the rooms original environment color.
See also: highlightRoom()

Note Note: Available since Mudlet 2.0 final release

Example
unHighlightRoom(4534)

Miscellaneous Functions

addSupportedTelnetOption

addSupportedTelnetOption(option)
Adds a telnet option, which when queried by a MUD server, Mudlet will return DO (253) on. Use this to register the telnet option that you will be adding support for with Mudlet - see additional protocols section for more.
Example
<event handlers that add support for MSDP... see http://www.mudbytes.net/index.php?a=topic&t=4104&p=63920#p63920 for an example>
 
-- register with Mudlet that it should not decline the request of MSDP support
local TN_MSDP = 69
addSupportedTelnetOption(TN_MSDP)

expandAlias

expandAlias(command,true/false)
Runs the command as if it was from the command line - so aliases are checked and if none match, it's sent to the the game. If the second argument is false, it will hide the command from being echoed back in your buffer. Defaults to true.
Example
expandAlias("t rat")
 
-- don't echo the command
expandAlias("t rat", false)

Note Note: If you want to be using the matches table after calling expandAlias, you should save it first as local oldmatches = matches before calling expandAlias, since expandAlias will overwrite it after using it again.

feedTriggers

feedTriggers( text )
This function will have Mudlet parse the given text as if it came from the MUD - one great application is trigger testing. You can use \n to represent a new line - you also want to use it before and after the text you’re testing, like so:
feedTriggers("\nYou sit yourself down.\n")
The function also accept ANSI color codes that are used in MUDs. A sample table can be found here.
Example
feedTriggers("\nThis is \27[1;32mgreen\27[0;37m, \27[1;31mred\27[0;37m, \27[46mcyan background\27[0;37m," ..
"\27[32;47mwhite background and green foreground\27[0;37m.\n")

getModulePriority

priority = getModulePriority(module name)
Returns the priority of a module as an integer. This determines the order modules will be loaded in - default is 0. Useful if you have a module that depends on another module being loaded first, for example.
See also: setModulePriority()
Example
getModulePriority("mudlet-mapper")

getMudletHomeDir

getMudletHomeDir()
Returns the current home directory of the current profile. This can be used to store data, save statistical information, or load resource files from packages.
Example
-- save a table
table.save(getMudletHomeDir().."/myinfo.dat", myinfo)
 
-- or access package data. The forward slash works even on Windows fine
local path = getMudletHomeDir().."/mypackagename"

installPackage

installPackage(location)
Installs a Mudlet XML or package.
Parameters
  • location:
Exact location of the xml or package to install.
See also: uninstallPackage()
Example
installPackage([[C:\Documents and Settings\bub\Desktop\myalias.xml]])

playSoundFile

playSoundFile(fileName)
This function plays a sound file. On 2.0, it can play most sound formats and up to 4 sounds simulaneously.
Parameters
  • fileName:
Exact path of the sound file.
Example
-- play a sound in Windows
playSoundFile([[C:\My folder\boing.wav]])
 
-- play a sound in Linux
playSoundFile([[/home/myname/Desktop/boingboing.wav]])
 
-- play a sound from a package
playSoundFile(getMudletHomeDir().. [[/mypackage/boingboing.wav]])

registerAnonymousEventHandler

registerAnonymousEventHandler(event name, function name)
Registers a function to an event handler, not requiring you to set one up via s cript.
At the moment, it's not possible to use handlers inside namespaces, or unregister them.
Example
-- example taken from the God Wars 2 (http://godwars2.org) Mudlet UI - forces the window to keep to a certain size
function keepStaticSize()
  setMainWindowSize(1280,720)
end -- keepStaticSize
 
registerAnonymousEventHandler("sysWindowResizeEvent", "keepStaticSize")

resetProfile

resetProfile()
Reloads your entire Mudlet profile - as if you've just opened it. All UI elements will be cleared, so this useful when you're coding your UI. To use this function, call it and then receive input from the game - that will trigger Mudlet to do the reset.

sendSocket

sendSocket(data)
Sends given binary data as-is to the MUD. You can use this to implement support for a new telnet protocol, simultronics login or etcetera.
Example
TN_IAC = 255
TN_WILL = 251
TN_DO = 253
TN_SB = 250
TN_SE = 240
TN_MSDP = 69
 
MSDP_VAL = 1
MSDP_VAR = 2
 
sendSocket( string.char( TN_IAC, TN_DO, TN_MSDP ) ) -- sends IAC DO MSDP
 
--sends: IAC  SB MSDP MSDP_VAR "LIST" MSDP_VAL "COMMANDS" IAC SE
local msg = string.char( TN_IAC, TN_SB, TN_MSDP, MSDP_VAR ) .. " LIST " ..string.char( MSDP_VAL ) .. " COMMANDS " .. string.char( TN_IAC, TN_SE )
sendSocket( msg )

spawn

spawn(read function, process to spawn)
Spawns a process and opens a communicatable link with it - read function is the function you'd like to use for reading output from the process, and t is a table containing functions specific to this connection - send(data), true/false = isRunning(), and close().
Example
-- simple example on a program that quits right away, but prints whatever it gets using the 'display' function
local f = spawn(display, "ls")
display(f.isRunning())
f.close()

uninstallPackage

uninstallPackage(name)
Uninstalls a Mudlet package with the given name.
See also: installPackage()
Example
uninstallPackage("myalias")

yajl.to_string

yajl.to_string(data)
Encodes a Lua table into JSON data and returns it as a string. This function is very efficient - if you need to encode into JSON, use this.
Example
-- on IRE MUDs, you can send a GMCP request to request the skills in a particular skillset. Here's an example:
sendGMCP("Char.Skills.Get "..yajl.to_string{group = "combat"})
 
-- you can also use it to convert a Lua table into a string, so you can, for example, store it as room's userdata
local toserialize = yajl.to_string(continents)
setRoomUserData(1, "areaContinents", toserialize)


yajl.to_value

yajl.to_value(data)
Decodes JSON data (as a string) into a Lua table. This function is very efficient - if you need to dencode into JSON, use this.
Example
-- given the serialization example above with yajl.to_string, you can deserialize room userdata back into a table
local tmp = getRoomUserData(1, "areaContinents")
if tmp == "" then return end
 
local continents = yajl.to_value(tmp)
display(continents)

Mudlet Object Functions

appendCmdLine

appendCmdLine()
Appends text to the main input line.
Example
-- adds the text "55 backpacks" to whatever is currently in the input line
appendCmdLine("55 backpacks")
 
-- makes a link, that when clicked, will add "55 backpacks" to the input line
echoLink("press me", "appendCmdLine'55 backpack'", "Press me!")

clearCmdLine

clearCmdLine()
Clears the input line of any text that's been entered.
Example
-- don't be evil with this!
clearCmdLine()

createStopWatch

createStopWatch()
This function creates a stop watch. It is high resolution time measurement tool. Stop watches can be started, stopped, reset and asked how much time has passed since the stop watch has been started.

Note Note: it's best to re-use stopwatch IDs if you can - Mudlet at the moment does not delete them, so creating more and more would use more memory.

Returns: The ID of a high resolution clock with milliseconds to measure time more accurately.
See also: startStopWatch(), stopStopWatch(), resetStopWatch(), getStopWatchTime()
Example
In a global script you create all stop watches that you need in your system and store the respective stopWatch-IDs in global variables:
fightStopWatch = createStopWatch() -- you store the watchID in a global variable to access it from anywhere
Then you can start the stop watch in some trigger/alias/script with:
startStopWatch( fightStopWatch )
To stop the watch and measure its time in e.g. a trigger script you can write:
fightTime = stopStopWatch( fightStopWatch )
echo( "The fight lasted for " .. fightTime .. " seconds." )
resetStopWatch( fightStopWatch )
You can also measure the elapsed time without having to stop the stop watch with getStopWatchTime.

disableAlias

disableAlias(name)
Disables/deactivates the alias by its name. If several aliases have this name, they'll all be disabled.
Parameters
  • name:
The name of the alias. Passed as a string.
Examples
--Disables the alias called 'my alias'
disableAlias("my alias")

disableKey

disableKey(name)
Disables key a key (macro) or a key group. When you disable a key group, all keys within the group will be implicitly disabled as well.
Parameters
  • name:
The name of the key or group to identify what you'd like to disable.
Examples
-- you could set multiple keys on the F1 key and swap their use as you wish by disabling and enabling them
disableKey("attack macro")
disableKey("jump macro")
enableKey("greet macro")

disableTimer

disableTimer(name)
Disables a timer from running it’s script when it fires - so the timer cycles will still be happening, just no action on them. If you’d like to permanently delete it, use killTrigger instead.
Parameters
  • name:
Expects the timer ID that was returned by tempTimer on creation of the timer or the name of the timer in case of a GUI timer.
Example
--Disables the timer called 'my timer'
disableTimer("my timer")

disableTrigger

disableTrigger(name)
Disables a permanent (one in the trigger editor) or a temporary trigger.
Parameters
  • name:
Expects the trigger ID that was returned by tempTrigger or other temp*Trigger variants, or the name of the trigger in case of a GUI trigger.
Example
-- Disables the trigger called 'my trigger'
disableTrigger("my trigger")

enableAlias

enableAlias(name)
Enables/activates the alias by it’s name. If several aliases have this name, they’ll all be enabled.
Parameters
  • name:
Expects the alias ID that was returned by tempTrigger on creation of the alias or the name of the alias in case of a GUI alias.
Example
--Enables the alias called 'my alias'
enableAlias("my alias")

enableKey

enableKey(name)
Enables a key (macro) or a group of keys (and thus all keys within it that aren't explicitly deactivated).
Parameters
  • name:
The name of the group that identifies the key.
-- you could use this to disable one key set for the numpad and activate another
disableKey("fighting keys")
enableKey("walking keys")

enableTimer

enableTimer(name)
Enables or activates a timer that was previously disabled.
Parameters
  • name:
Expects the timer ID that was returned by tempTimer on creation of the timer or the name of the timer in case of a GUI timer.
-- enable the timer called 'my timer' that you created in Mudlets timers section
enableTimer("my timer")
-- or disable & enable a tempTimer you've made
timerID = tempTimer(10, [[echo("hi!")]])
 
-- it won't go off now
disableTimer(timerID)
-- it will continue going off again
enableTimer(timerID)

enableTrigger

enableTrigger(name)
Enables or activates a trigger that was previously disabled.
Parameters
  • name:
Expects the trigger ID that was returned by tempTrigger or by any other temp*Trigger variants, or the name of the trigger in case of a GUI trigger.
-- enable the trigger called 'my trigger' that you created in Mudlets triggers section
enableTrigger("my trigger")
-- or disable & enable a tempTrigger you've made
triggerID = tempTrigger("some text that will match in a line", [[echo("hi!")]])
 
-- it won't go off now when a line with matching text comes by
disableTrigger(triggerID)
 
-- and now it will continue going off again
enableTrigger(triggerID)

exists

exists(name, type)
Tells you how many things of the given type exist.
Parameters
  • name:
The name or the id returned by tempTimer to identify the item.
  • type:
The type can be 'alias', 'trigger', or 'timer'.
Example
echo("I have " .. exists("my trigger", "trigger") .. " triggers called 'my trigger'!")
You can also use this alias to avoid creating duplicate things, for example:
-- this code doesn't check if an alias already exists and will keep creating new aliases
permAlias("Attack", "General", "^aa$", [[send ("kick rat")]])
 
-- while this code will make sure that such an alias doesn't exist first
-- we do == 0 instead of 'not exists' because 0 is considered true in Lua
if exists("Attack", "alias") == 0 then
    permAlias("Attack", "General", "^aa$", [[send ("kick rat")]])
end

getButtonState

getButtonState()
This function can be used in checkbox button scripts (2-state buttons) to determine the current state of the checkbox.
Returns 2 if button is checked, and 1 if it's not.
Example
checked = getButtonState();
if checked == 1 then
    hideExits()
else
    showExits()
end;

invokeFileDialog

invokeFileDialog(fileOrFolder, dialogTitle)
Opens a file chooser dialog, allowing the user to select a file or a folder visually. The function returns the selected path or "" if there was none chosen.
Parameters
  • fileOrFolder: true for file selection, false for folder selection.
  • dialogTitle: the code to do when the timer is up - wrap it in [[ ]], or provide a Lua function
Examples
function whereisit()
  local path = invokeFileDialog(false, "Where should we save the file? Select a folder and click Open")
 
  if path == "" then return nil else return path end
end

isActive

isActive(name, type)
You can use this function to check if something, or somethings, are active.
Returns the number of active things - and 0 if none are active. Beware that all numbers are true in Lua, including zero.
Parameters
  • name:
The name or the id returned by tempTimer to identify the item.
  • type:
The type can be 'alias', 'trigger', or 'timer'.
Example
echo("I have " .. isActive("my trigger", "trigger") .. " currently active trigger(s) called 'my trigger'!")

isPrompt

isPrompt()
Returns true or false depending on if the current line being processed is a prompt. This infallible feature is available for MUDs that supply GA events (to check if yours is one, look to bottom-right of the main window - if it doesn’t say <No GA>, then it supplies them).
Example use could be as a Lua function, making closing gates on a prompt real easy.
Example
-- make a trigger pattern with 'Lua function', and this will trigger on every prompt!
return isPrompt()

killAlias

killAlias(name)
Deletes an alias with the given name. If several aliases have this name, they'll all be deleted.
Parameters
  • name:
The name or the id returned by tempTimer to identify the alias.
--Deletes the alias called 'my alias'
killAlias("my alias")

killTimer

killTimer(id)
Deletes a tempTimer.

Note Note: Non-temporary timers that you have set up in the GUI cannot be deleted with this function. Use disableTimer() and enableTimer() to turn them on or off.

Parameters
Returns true on success and false if the timer id doesn’t exist anymore (timer has already fired) or the timer is not a temp timer.
Example
-- create the timer and remember the timer ID
timerID = tempTimer(10, [[echo("hello!")]])
 
-- delete the timer
if killTimer(timerID) then echo("deleted the timer") else echo("timer is already deleted") end

killTrigger

killTrigger(id)
Deletes a tempTrigger, or a trigger made with one of the temp<type>Trigger() functions.

Note Note: When used in out of trigger contexts, the triggers are disabled and deleted upon the next line received from the game - so if you are testing trigger deletion within an alias, the 'statistics' window will be reporting trigger counts that are disabled and pending removal, and thus are no cause for concern.

Parameters
  • id:
The ID returned by tempTimer to identify the item. ID is a string and not a number.
Returns true on success and false if the trigger id doesn’t exist anymore (trigger has already fired) or the trigger is not a temp trigger.

permAlias

permAlias(name, parent, regex, lua code)
Creates a persistent alias that stays after Mudlet is restarted and shows up in the Script Editor.
Parameters
  • name:
The name you’d like the alias to have.
  • parent:
The name of the group, or another alias you want the trigger to go in - however if such a group/alias doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
  • regex:
The pattern that you’d like the alias to use.
  • lua code:
The script the alias will do when it matches.
Example
-- creates an alias called "new alias" in a group called "my group"
permAlias("new alias", "my group", "^test$", [[echo ("say it works! This alias will show up in the script editor too.")]])

Note Note: Mudlet by design allows duplicate names - so calling permAlias with the same name will keep creating new aliases. You can check if an alias already exists with the exists function.

permGroup

permGroup(name, itemtype)
Creates a new group of a given type at the root level (not nested in any other groups). This group will persist through Mudlet restarts.
Parameters
  • name:
The name of the new group you want to create.
  • itemtype:
The name of the timer, trigger, or alias.

Note Note: Added to Mudlet in the 2.0 final release.

--create a new trigger group
permGroup("Combat triggers", "trigger")
 
--create a new alias group only if one doesn't exist already
if exists("Defensive aliases", "alias") == 0 then
  permGroup("Defensive aliases", "alias")
end

permRegexTrigger

permRegexTrigger(name, parent, pattern, lua code)
Creates a persistent trigger with a regex pattern that stays after Mudlet is restarted and shows up in the Script Editor.
Parameters
  • name is the name you’d like the trigger to have.
  • parent is the name of the group, or another trigger you want the trigger to go in - however if such a group/trigger doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
  • pattern table is a table of patterns that you’d like the trigger to use - it can be one or many.
  • lua code is the script the trigger will do when it matches.
Example
-- Create a regex trigger that will match on the prompt to record your status
permRegexTrigger("Prompt", "", {"^(\d+)h, (\d+)m"}, [[health = tonumber(matches[2]); mana = tonumber(matches[3])]])

Note Note: Mudlet by design allows duplicate names - so calling permRegexTrigger with the same name will keep creating new triggers. You can check if a trigger already exists with the exists() function.

permSubstringTrigger

permSubstringTrigger( name, parent, pattern, lua code )
Creates a persistent trigger with a substring pattern that stays after Mudlet is restarted and shows up in the Script Editor.
Parameters
  • name is the name you’d like the trigger to have.
  • parent is the name of the group, or another trigger you want the trigger to go in - however if such a group/trigger doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
  • pattern table is a table of patterns that you’d like the trigger to use - it can be one or many.
  • lua code is the script the trigger will do when it matches.
Example
-- Create a trigger to highlight the word "pixie" for us
permSubstringTrigger("Highlight stuff", "General", {"pixie"},
[[selectString(line, 1) bg("yellow") resetFormat()]])
 
-- Or another trigger to highlight several different things
permSubstringTrigger("Highlight stuff", "General", {"pixie", "cat", "dog", "rabbit"},
[[selectString(line, 1) fg ("blue") bg("yellow") resetFormat()]])

Note Note: Mudlet by design allows duplicate names - so calling permSubstringTrigger with the same name will keep creating new triggers. You can check if a trigger already exists with the exists() function.

permTimer

permTimer(name, parent, seconds, lua code)
Creates a persistent timer that stays after Mudlet is restarted and shows up in the Script Editor.
Parameters
  • name
Is the name of the timer.
  • parent
Is the name of the timer group you want the timer to go in..
  • seconds
Is a number specifying a delay after which the timer will do the lua code you give it as a string.
  • lua code is the code with string you are doing this to.
Example
-- create a timer in the "first timer group" group
permTimer("my timer", "first timer group", 4.5, [[send ("my timer that's in my first timer group fired!")]])
-- create a timer that's not in any group; just at the top
permTimer("my timer", "", 4.5, [[send ("my timer that's in my first timer group fired!")]])

Note Note: Mudlet by design allows duplicate names - so calling permTimer with the same name will keep creating new timers. You can check if a timer already exists with the exists() function.

printCmdLine

printCmdLine(text)
Replaces the current text in the input line, and sets it to the given text.
printCmdLine("say I'd like to buy ")

raiseEvent

raiseEvent(event_name, arg-1, … arg-n)
Raises the event event_name. The event system will call the main function (the one that is called exactly like the script name) of all such scripts that have registered event handlers. If an event is raised, but no event handler scripts have been registered with the event system, the event is ignored and nothing happens. This is convenient as you can raise events in your triggers, timers, scripts etc. without having to care if the actual event handling has been implemented yet - or more specifically how it is implemented. Your triggers raise an event to tell the system that they have detected a certain condition to be true or that a certain event has happened. How - and if - the system is going to respond to this event is up to the system and your trigger scripts don’t have to care about such details. For small systems it will be more convenient to use regular function calls instead of events, however, the more complicated your system will get, the more important events will become because they help reduce complexity very much.
The corresponding event handlers that listen to the events raised with raiseEvent() need to use the script name as function name and take the correct number of arguments.


Example
raiseEvent("fight") a correct event handler function would be: myScript( event_name ). In this example raiseEvent uses minimal arguments, name the event name. There can only be one event handler function per script, but a script can still handle multiple events as the first argument is always the event name. So you can call your own special handlers for individual events. The reason behind this is that you should rather use many individual scripts instead of one huge script that has all your function code etc. Scripts can be organized very well in trees and thus help reduce complexity on large systems.

resetStopWatch

resetStopWatch(watchID)
This function resets the time to 0:0:0.0, but does not start the stop watch. You can start it with startStopWatch createStopWatch

setConsoleBufferSize

setConsoleBufferSize( consoleName, linesLimit, sizeOfBatchDeletion )
Sets the maximum number of lines a buffer (main window or a miniconsole) can hold.
Parameters
  • consoleName:
The name of the window
  • linesLimit:
Sets the amount of lines the buffer should have.

Note Note: Mudlet performs extremely efficiently with even huge numbers, so your only limitation is your computers memory (RAM).

  • sizeOfBatchDeletion:
Specifies how many lines should Mudlet delete at once when you go over the limit - it does it in bulk because it's efficient to do so.
Example
-- sets the main windows size to 5 million lines maximum - which is more than enough!
setConsoleBufferSize("main", 5000000, 1000)

setTriggerStayOpen

setTriggerStayOpen(name, number)
Sets for how many more lines a trigger script should fire or a chain should stay open after the trigger has matched - so this allows you to extend or shorten the fire length of a trigger. The main use of this function is to close a chain when a certain condition has been met.
Parameters
  • name: The name of the trigger which has a fire length set (and which opens the chain).
  • number: 0 to close the chain, or a positive number to keep the chain open that much longer.
Examples
-- if you have a trigger that opens a chain (has some fire length) and you'd like it to be closed 
-- on the next prompt, you could make a trigger inside the chain with a Lua function pattern of:
return isPrompt()
-- and a script of:
setTriggerStayOpen("''Parent trigger name''", 0)
-- to close it on the prompt!

startStopWatch

startStopWatch( watchID )
Starts the stop watch. Stopwatches can be stopped and re-started any number of times.
See also: createStopWatch(), stopStopWatch()
Parameters
Examples
-- this is a common pattern for re-using stopwatches and starting them:
watch = watch or createStopWatch()
startStopWatch(watch)

stopStopWatch

stopStopWatch( watchID )
Stops the stop watch and returns the elapsed time in milliseconds in form of 0.001. You can also retrieve the current time without stopping the stopwatch with getStopWatchTime().
Returns time as a number.
See also: createStopWatch(), getStopWatchTime()
Parameters
Examples
-- this is a common pattern for re-using stopwatches and starting them:
watch = watch or createStopWatch()
startStopWatch(watch)
 
-- do some long-running code here ...
 
print("The code took: "..stopStopWatch(watch).."s to run.")

tempAlias

aliasID = tempAlias(regex, code to do)
Creates a temporary alias - temporary in the sense that it won't be saved when Mudlet restarts (unless you re-create it). The alias will go off as many times as it matches, it is not a one-shot alias. The function returns an ID for subsequent enableAlias(), disableAlias() and killAlias() calls.
Parameters
  • regex: Alias pattern in regex.
  • code to do: The code to do when the alias fires - wrap it in [[ ]].
Examples
myaliasID = tempAlias("^hi$", [[send ("hi") echo ("we said hi!")]])
 
-- you can also delete the alias later with:
killAlias(myaliasID)

tempBeginOfLineTrigger

tempBeginOfLineTrigger(part of line, code to do)
Creates a trigger that will go off whenever the part of line it's provided with matches the line right from the start (doesn't matter what the line ends with). This trigger isn't temporary in the sense that it'll go off only once (it'll go off as often as it matches), but rather it won't be saved when Mudlet is closed. The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls. The trigger will go off multiple times until you disable or destroy it.
Parameters
  • part of line: Start of the line that you'd like to match.
  • code to do: The code to do when the trigger fires - wrap it in [[ ]].
Examples
mytriggerID = tempBeginOfLineTrigger("Hello", [[echo("We matched!")]])
 
--[[ now this trigger will match on any of these lines:
Hello
Hello!
Hello, Bob!
 
but not on:
Oh, Hello
Oh, Hello!
]]

tempColorTrigger

tempColorTrigger(foregroundColor, backgroundColor, code)
Makes a color trigger that triggers on the specified foreground and background color. Both colors need to be supplied in form of these simplified ANSI 16 color mode codes. The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls. The trigger will go off multiple times until you disable or destroy it.
Parameters
  • foregroundColor: The foreground color you'd like to trigger on.
  • backgroundColor: The background color you'd like to trigger on.
  • code: The code you'd like the trigger to run, as a string.
Color codes
0 = default text color
1 = light black
2 = dark black
3 = light red
4 = dark red
5 = light green
6 = dark green
7 = light yellow
8 = dark yellow
9 = light blue
10 = dark blue
11 = light magenta
12 = dark magenta
13 = light cyan
14 = dark cyan
15 = light white
16 = dark white
Examples
-- This script will re-highlight all text in blue foreground colors on a black background with a red foreground color
-- on a blue background color until another color in the current line is being met. temporary color triggers do not 
-- offer match_all or filter options like the GUI color triggers because this is rarely necessary for scripting. 
-- A common usage for temporary color triggers is to schedule actions on the basis of forthcoming text colors in a particular context.
tempColorTrigger(9,2,[[selectString(matches[1],1); fg("red"); bg("blue");]] );


tempComplexRegexTrigger

tempComplexRegexTrigger('name', regex, code to execute, multiline, foreground color, bg color, filter, match all, highlight foreground color, highlight background color, play sound file, fire length, line delta)
Allows you to create a temporary trigger in Mudlet, using any of the UI-available options.
Returns the trigger name, that you can use killTrigger() later on with.
For the multiline and so on options, use a 0 if you don't want those options. Otherwise enter the value you want to use.
For color, you need to provide both fg and bg together.
For making multiline triggers, use the same trigger name an options, providing the new pattern to add:
tempComplexRegexTrigger("testTrigger", "first pattern", [[echo("it went")]], 1, 0, 0....)
tempComplexRegexTrigger("testTrigger", "second pattern", [[echo("it went")]], 1, 0, 0....)
That will make 1 trigger with both regex patterns. Note only one script will ever be used (the last one set).


tempExactMatchTrigger

tempExactMatchTrigger(exact line, code to do)
Creates a trigger that will go off whenever the line from the game matches the provided line exactly (ends the same, starts the same, and looks the same). You don't need to use any of the regex symbols here (^ and $). This trigger isn't temporary in the sense that it'll go off only once (it'll go off as often as it matches), but rather it won't be saved when Mudlet is closed. The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls. The trigger will go off multiple times until you disable or destroy it.
Parameters
  • exact line: Exact line you'd like to match.
  • code to do: The code to do when the trigger fires - wrap it in [[ ]].
Examples
mytriggerID = tempExactMatchTrigger("You have recovered balance on all limbs.", [[echo("We matched!")]])

tempLineTrigger

tempLineTrigger( from, howMany, LuaCode )
Temporary trigger that will fire on n consecutive lines following the current line. This is useful to parse output that is known to arrive in a certain line margin or to delete unwanted output from the MUD - the trigger does not require any patterns to match on. The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls. The trigger will go off multiple times until you disable or destroy it.
Returns trigger ID as a string.

Note Note: You can use this ID to enable/disable or kill this trigger later on.

Example
--Will fire 3 times with the line from the MUD.
tempLineTrigger( 1, 3, ) 
 
--Will fire 20 lines after the current line and fire twice on 2 consecutive lines.
tempLineTrigger( 20, 2, )

tempRegexTrigger

tempRegexTrigger(regex, code to do)
Creates a temporary regex trigger that executes the code whenever it matches. The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls. The trigger will go off multiple times until you disable or destroy it.
Parameters
  • regex: The regular expression that lines will be matched on.
  • code to do: The code to do when the timer is up - wrap it in [[ ]].
Examples
-- create a non-duplicate trigger that matches on any line and calls a function
html5log = html5log or {}
if html5log.trig then killTrigger(html5log.trig) end
html5log.trig = tempRegexTrigger("^", "html5log.recordline()")

tempTimer

tempTimer(time, code to do)
Creates a temporary one-shot timer and returns the timer ID, which you can use with enableTimer(), disableTimer() and killTimer() functions. You can use 2.3 seconds or 0.45 etc. After it has fired, the timer will be deactivated and destroyed, so it will only go off once. See here for a more detailed introduction to tempTimer.
Parameters
  • time: The time in seconds for which to set the timer for - you can use decimals here for precision. The timer will go off x given seconds after you make it.
  • code to do: The code to do when the timer is up - wrap it in [[ ]], or provide a Lua function.
Examples
-- wait half a second and then run the command
tempTimer( 0.5, [[send("kill monster")]] )
 
-- or an another example - two ways to 'embed' variable in a code for later:
local name = matches[2]
tempTimer(2, [[send("hello, ]]..name..[[ !")]])
-- or:
tempTimer(2, function()
  send("hello, "..name)
end)

Note Note: Double brackets, e.g: [[ ]] can be used to quote strings in Lua. The difference to the usual `" " quote syntax is that `[[ ]] also accepts the character ". Consequently, you don’t have to escape the " character in the above script. The other advantage is that it can be used as a multiline quote, so your script can span several lines.

Note Note: Lua code that you provide as an argument is compiled from a string value when the timer fires. This means that if you want to pass any parameters by value e.g. you want to make a function call that uses the value of your variable myGold as a parameter you have to do things like this:

tempTimer( 3.8, [[echo("at the time of the tempTimer call I had ]] .. myGold .. [[ gold.")]] )
 
-- tempTimer also accepts functions (and thus closures) - which can be an easier way to embed variables and make the code for timers look less messy:
 
local variable = matches[2]
tempTimer(3, function () send("hello, " .. variable) end)

tempTrigger

tempTrigger(substring, code to do)
Creates a temporary substring trigger that executes the code whenever it matches. The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls. The trigger will go off multiple times until you disable or destroy it.
Parameters
  • substring:: The substring to look for - this means a part of the line. If your provided text matches anywhere within the line from the game, the trigger will go off.
  • code to do: The code to do when the timer is up - wrap it in [[ ]].

Example:

-- this example will highlight the contents of the "target" variable.
-- It will also delete the previous trigger it made when you call it again, so you're only ever highlighting one name
if id then killTrigger(id) end
id = tempTrigger(target, [[selectString("]] .. target .. [[", 1) fg("gold") resetFormat()]])
-- a simpler trigger to replace "hi" with "bye" whenever you see it
tempTrigger("hi", [[selectString("hi", 1) replace("bye")]])

tempButton

tempButton(group name, button text, orientation)
Creates a temporary button.
Parameters
  • group name:: The toolbar to place the button into.
  • button text: The text to place on the button.
  • orientation: a number, 0 - horizontal orientation for the button, or 1 - vertical orientation for the button.

Networking Functions

A collection of functions for managing networking.

disconnect

disconnect()
Disconnects you from the game right away. Note that this will not properly log you out of the game.
See also: reconnect()
Example
disconnect()

downloadFile

downloadFile(saveto, url)
Downloads the resource at the given url into the saveto location on disk. This does not pause the script until the file is downloaded - instead, it lets it continue right away and downloads in the background. When a download is finished, the sysDownloadDone event is raised (with the saveto location as the argument), or when a download fails, the sysDownloadError event is raised with the reason for failure. You may call downloadFile multiple times and have multiple downloads going on at once - but they aren’t guaranteed to be downloaded in the same order that you started them in.

Note Note: Requires Mudlet 2.0+

Example
-- this example will check the Imperian homepage to see how many players are on right now
 
-- in an alias, download the Imperian homepage for stats processing
downloadFile(getMudletHomeDir().."/page.html", "http://www.imperian.com/")
 
-- then create a new script with the name of downloaded_file, add the event handler
-- for sysDownloadDone, and use this to parse the webpage and display the amount
function downloaded_file(_, filename)
  -- is the file that downloaded ours?
  if not filename:match("page", 1, true) then return end
 
  -- parse our ownloaded file for the player count
  io.input(filename)
  local s = io.read("*all")
  local pc = s:match([[<a href='players.php%?search=who'>(%d+)</a>]])
  display("Imperian has "..tostring(pc).." players on right now.")
  io.open():close()
  os.remove(filename)
end

getNetworkLatency

getNetworkLatency()
Returns the last measured response time between the sent command and the server reply e.g. 0.058 (=58 milliseconds lag) or 0.309 (=309 milliseconds). Also known as server lag.
Example

Need example

openUrl

openUrl (url)
Opens the default OS browser for the given URL.
Example
openUrl("http://google.com")
openUrl("www.mudlet.org")

reconnect

reconnect()
Force-reconnects (so if you're connected, it'll disconnect) you to the game.
Example
-- you could trigger this on a log out message to reconnect, if you'd like
reconnect()

sendAll

sendAll(list of things to send, [echo back or not])
send()'s a list of things to the game. If you'd like the commands not to be shown, include false at the end.
Example
-- instead of using many send() calls, you can use one sendAll
sendAll("outr paint", "outr canvas", "paint canvas")
-- can also have the commands not be echoed
sendAll("hi", "bye", false)

sendGMCP

sendGMCP(command)
Sends a GMCP message to the server. The IRE document on GMCP has information about what can be sent, and what tables it will use, etcetera.
See Also: GMCP Scripting
Example
--This would send "Core.KeepAlive" to the server, which resets the timeout
sendGMCP("Core.KeepAlive")
 
--This would send a request for the server to send an update to the gmcp.Char.Skills.Groups table.
sendGMCP("Char.Skills.Get {}")
 
--This would send a request for the server to send a list of the skills in the 
--vision group to the gmcp.Char.Skills.List table.
 
sendGMCP([[Char.Skills.Get { "group": "vision"}]])
 
--And finally, this would send a request for the server to send the info for 
--hide in the woodlore group to the gmcp.Char.Skills.Info table
 
sendGMCP([[Char.Skills.Get { "group": "woodlore", "name": "hide"}]])

sendIrc

sendIrc(channel, message)
Sends a message to an IRC channel or person. You must have the IRC window open, and if speaking to a channel, be joined in that channel. IRC currently only works on the freenode network and password-protected channels aren't supported.
Parameters
  • channel:
The channel to send the message to. Can be #<channelname> to send to a channel, or <person name> to send to a person. Passed as a string.
  • message:
The message to send. Passed as a string.
Example
--This would send "hello from Mudlet!" to the channel #mudlet on freenode.net
sendIrc("#mudlet", "hello from Mudlet!")
--This would send "identify password" in a private message to Nickserv on freenode.net
sendIrc("Nickserv", "identify password")

sendTelnetChannel102

sendTelnetChannel102(msg)
Sends a message via the 102 subchannel back to the MUD (that's used in Aardwolf). The msg is in a two byte format - see `help telopts` in Aardwolf on how that works.
Example
-- turn prompt flags on:
sendTelnetChannel102("\52\1")
 
-- turn prompt flags off:
sendTelnetChannel102("\52\2")

String Functions

string.byte

string.byte(string [, i [, j]])
mystring:byte([, i [, j]])
Returns the internal numerical codes of the characters s[i], s[i+1], ···, s[j]. The default value for i is 1; the default value for j is i.
Note that numerical codes are not necessarily portable across platforms.
See also: string.char
Example
--The following call will return the ASCII values of "A", "B" and "C" 
a, b, c = string.byte("ABC", 1, 3)
 
echo(a .. " - " .. b .. " - " .. c) -- echos "65 - 66 - 67"

string.char

string.char(···)
Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument.

Note Note: Numerical codes are not necessarily portable across platforms.

See also: string.byte
Example
--The following call will return the string "ABC" corresponding to the ASCII values 65, 66, 67
mystring = string.char(65, 66, 67)

string.cut

string.cut(string, maxLen)
Cuts string to the specified maximum length.
Returns the modified string.
Parameters
  • string:
The text you wish to cut. Passed as a string.
  • maxLen:
The maximum length you wish the string to be. Passed as an integer number.
Example
--The following call will return 'abc' and store it in myString
mystring = string.cut("abcde", 3)
--You can easily pad string to certain length. Example below will print 'abcde     ' e.g. pad/cut string to 10 characters.
local s = "abcde"
s = string.cut(s .. "          ", 10)   -- append 10 spaces
echo("'" .. s .. "'")

string.dump

string.dump()

Converts a function into a binary string. You can use the loadstring() function later to get the function back.

Example
string = string.dump(echo("this is a string"))
--The following should then echo "this is a string"
loadstring(string)()

string.enclose

string.enclose(String)
Wraps a string with [[ ]]
Returns the altered string.
Parameters
  • String:
The string to enclose. Passed as a string.
Example
--This will echo '[[Oh noes!]]' to the main window
echo("'" .. string.enclose("Oh noes!") .. "'")

string.ends

string.ends(String, Suffix)
Test if string is ending with specified suffix.
Returns true or false.
See also: string.starts
Parameters
  • String:
The string to test. Passed as a string.
  • Suffix:
The suffix to test for. Passed as a string.
Example
--This will test if the incoming line ends with "in bed" and if not will add it to the end.
if not string.ends(line, "in bed") then
  echo("in bed\n")
end

string.find

string.find()
Need description
Example

Need example

string.findPattern

string.findPattern(text, pattern)
Return first matching substring or nil.
Parameters
  • text:
The text you are searching the pattern for.
  • pattern:
The pattern you are trying to find in the text.
Example

Following example will print: "I did find: Troll" string.

local match = string.findPattern("Troll is here!", "Troll")
if match then
   echo("I did find: " .. match)
end
This example will find substring regardless of case.
local match = string.findPattern("Troll is here!", string.genNocasePattern("troll"))
if match then
    echo("I did find: " .. match)
end
  • Return value:
nil or first matching substring

See also: string.genNocasePattern()

string.format

string.format()
Need description here.
Example

Need example

string.genNocasePattern

string.genNocasePattern(s)
Generate case insensitive search pattern from string.
Parameters
  • s:
Example
Following example will generate and print "123[aA][bB][cC]" string.
echo(string.genNocasePattern("123abc"))
  • Return value:
case insensitive pattern string

string.gfind

string.gfind()
Need description here.
Example

Need example

string.gmatch

string.gmatch()
Need description here.
Example

Need example

string.gsub

string.gsub()
Need description here.
Example

Need example

string.len

string.len(String)
mystring:len()
Receives a string and returns its length. The empty string "" has length 0. Embedded zeros are counted, so "a\000bc\000" has length 5.
Parameters
  • String:
The string you want to find the length of. Passed as a string.
Example

Need example

string.lower

string.lower(String)
mystring:lower()
Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged. The definition of what an uppercase letter is depends on the current locale.
See also: string.upper
Example

Need example

string.match

string.match()
Need description here.
Example

Need example

string.rep

string.rep(String, n)
mystring:rep(n)
Returns a string that is the concatenation of n copies of the string String.
Example

Need example

string.reverse

string.reverse(string)
mystring:reverse()
Returns a string that is the string string reversed.
Parameters
  • string:
The string to reverse. Passed as a string.
Example
mystring = "Hello from Lua"
echo(mystring:reverse()) -- displays 'auL morf olleH'

string.split

string.split(string, delimiter)
myString:split(delimiter)
Splits a string into a table by the given delimiter. Can be called against a string (or variable holding a string) using the second form above.
Returns a table containing the split sections of the string.
Parameters
  • string:
The string to split. Parameter is not needed if using second form of the syntax above. Passed as a string.
  • delimiter:
The delimiter to use when splitting the string. Passed as a string, and allows for Lua pattern types. Use % to escape here (and %% to escape a stand-alone %).
Example
-- This will split the string by ", " delimiter and print the resulting table to the main window.
names = "Alice, Bob, Peter"
name_table = string.split(names, ", ")
display(name_table)
 
--The alternate method
names = "Alice, Bob, Peter"
name_table = names:split(", ")
display(name_table)
Either method above will print out:
table {
1: 'Alice'
2: 'Bob'
3: 'Peter'
}

string.starts

string.starts(string, prefix)
Test if string is starting with specified prefix.
Returns true or false
See also: string.ends
Parameters
  • string:
The string to test. Passed as a string.
  • prefix:
The prefix to test for. Passed as a string.
Example
--The following will see if the line begins with "You" and if so will print a statement at the end of the line
if string.starts(line, "You") then
  echo("====oh you====\n")
end

string.sub

string.sub()
Need description here.
Example

Need example

string.title

string.title(string)
string:title()
Capitalizes the first character in a string.
Returns the altered string.
Parameters
  • string:
The string to modify. Not needed if you use the second form of the syntax above.
Example
--Variable testname is now Anna.
testname = string.title("anna")
--Example will set test to "Bob".
test = "bob"
test = test:title()

string.trim

string.trim(string)
Trims string, removing all 'extra' white space at the beginning and end of the text.
Returns the altered string.
Parameters
  • string:
The string to trim. Passed as a string.
Example
--This will print 'Troll is here!', without the extra spaces.
local str = string.trim("  Troll is here!  ")
echo("'" .. str .. "'")

string.upper

string.upper(string)
mystring:upper()
Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged. The definition of what a lowercase letter is depends on the current locale.
Parameters
  • string:
The string you want to change to uppercase
Example
-- displays 'RUN BOB RUN'
local str = string.upper("run bob run")
See also: string.lower

Table Functions

table.complement

table.complement (set1, set2)
Returns a table that is the relative complement of the first table with respect to the second table. Returns a complement of key/value pairs.
Parameters
  • table1:
  • table2:

table.concat

table.concat(table, delimiter, startingindex, endingindex)
Joins a table into a string. Each item must be something which can be transformed into a string.
Returns the joined string.
See also: string.split
Parameters
  • table:
The table to concatenate into a string. Passed as a table.
  • delimiter:
Optional string to use to separate each element in the joined string. Passed as a string.
  • startingindex:
Optional parameter to specify which index to begin the joining at. Passed as an integer.
  • endingindex:
Optional parameter to specify the last index to join. Passed as an integer.
Examples
--This shows a basic concat with none of the optional arguments
testTable = {1,2,"hi","blah",}
testString = table.concat(testTable)
--testString would be equal to "12hiblah"
 
--This example shows the concat using the optional delimiter
testString = table.concat(testTable, ", ")
--testString would be equal to "1, 2, hi, blah"
 
--This example shows the concat using the delimiter and the optional starting index
testString = table.concat(testTable, ", ", 2)
--testString would be equal to "2, hi, blah"
 
--And finally, one which uses all of the arguments
testString = table.concat(testTable, ", ", 2, 3)
--testString would be equal to "2, hi"

table.contains

table.contains (t, value)
Determines if a table contains a value as a key or as a value (recursive).
Returns true or false
Parameters
  • t:
The table in which you are checking for the presence of the value.
  • value:
The value you are checking for within the table.
Example
local test_table = { "value1", "value2", "value3", "value4" }
if table.contains(test_table, "value1") then 
   echo("Got value 1!")
else
   echo("Don't have it. Sorry!")
end

This example would always echo the first one, unless you remove value1 from the table.

table.foreach

table.intersection

table.insert

table.insert(table, [pos,] value)
Inserts element value at position pos in table, shifting up other elements to open space, if necessary. The default value for pos is n+1, where n is the length of the table, so that a call table.insert(t,x) inserts x at the end of table t.
See also: table.remove
Parameters
  • table:
The table in which you are inserting the value
  • pos:
Optional argument, determining where the value will be inserted.
  • value:
The variable that you are inserting into the table. Can be a regular variable, or even a table or function*.

Note Note: Inserting a function into a table is not good coding practice, and will not turn out how you think it would. Make sure to only do that if you know what you're doing!

table.index_of

table.index_of(table, value)

Returns the index (location) of an item in an indexed table, or nil if it's not found.

Parameters
  • table:
The table in which you are inserting the value
  • value:
The variable that you are searching for in the table.
Examples
-- will return 1, because 'hi' is the first item in the list
table.index_of({"hi", "bye", "greetings"}, "hi")
 
-- will return 3, because 'greetings' is third in the list
table.index_of({"hi", "bye", "greetings"}, "greetings")
 
-- you can also use this in combination with table.remove(), which requires the location of the item to delete
local words = {"hi", "bye", "greetings"}
table.remove(words, table.index_of(words, "greetings"))
 
-- however that won't work if the word isn't present, table.remove(mytable, nil (from table.index_of)) will give an error
-- so if you're unsure, confirm with table.contains first
local words = {"hi", "bye", "greetings"}
if table.contains(words, "greetings") then
  table.remove(words, table.index_of(words, "greetings"))
end

table.is_empty

table.is_empty(table)
Check if a table is devoid of any values.
Parameters
  • table:
The table you are checking for values.

table.load

table.load(location, table)
Load a table from an external file into mudlet.
See also: table.save
Parameters
  • location:
Where you are loading the table from. Can be anywhere on your computer.
  • table:
The table that you are loading into - it must exist already.
Example:
-- This will load the table mytable from the lua file mytable present in your Mudlet Home Directory.
mytable = mytable or {}
table.load(getMudletHomeDir().."/mytable.lua", mytable) -- using / is OK on Windows too.
-- You can load a table from anywhere on your computer, but it's preferable to have them consolidated somewhere connected to Mudlet.

table.maxn

table.maxn(table)
Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.)

table.n_union

table.n_union (table1, table2)
Returns a numerically indexed table that is the union of the provided tables (that is - merges two indexed lists together). This is a union of unique values. The order and keys of the input tables are not preserved.
Parameters
  • table1: the first table as an indexed list.
  • table2: the second table as an indexed list.
Example
display(table.n_union({"bob", "mary"}, {"august", "justinian"}))
 
{
  "bob",
  "mary",
  "august",
  "justinian"
}

table.n_complement

Returns a table that is the relative complement of the first table with respect to the second table. Returns a complement of values.

table.n_intersection

table.n_intersection(...)
Returns a numerically indexed table that is the intersection of the provided tables. This is an intersection of unique values. The order and keys of the input tables are not preserved.

table.pickle

table.pickle( t, file, tables, lookup )
Internal function used by table.save() for serializing data.

table.remove

table.remove(table, value_position)
Remove a value from an indexed table, by the values position in the table.
See also: table.insert
Parameters
  • table
The indexed table you are removing the value from.
  • value_position
The indexed number for the value you are removing.
Example
testTable = { "hi", "bye", "cry", "why" }
table.remove(testTable, 1) -- will remove hi from the table
-- new testTable after the remove
testTable = { "bye", "cry", "why" }
-- original position of hi was 1, after the remove, position 1 has become bye
-- any values under the removed value are moved up, 5 becomes 4, 4 becomes 3, etc

Note Note: To remove a value from a key-value table, it's best to simply change the value to nil.

testTable = { test = "testing", go = "boom", frown = "glow" }
table.remove(testTable, test) -- this will error
testTable.test = nil -- won't error
testTable["test"] = nil -- won't error

table.save

table.save(location, table)
Save a table into an external file in location.
See also: table.load
Parameters
  • location:
Where you want the table file to be saved. Can be anywhere on your computer.
  • table:
The table that you are saving to the file.
Example:
-- Saves the table mytable to the lua file mytable in your Mudlet Home Directory
table.save(getMudletHomeDir().."/mytable.lua", mytable)

table.sort

table.sort(Table [, comp])
Sorts table elements in a given order, in-place, from Table[1] to Table[n], where n is the length of the table.
If comp is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that not comp(a[i+1],a[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead.
The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.

table.size

table.size (t)
Returns the size of a key-value table (this function has to iterate through all of the table to count all elements).
Returns a number.
Parameters
  • t:
The table you are checking the size of.

Note Note: For index based tables you can get the size with the # operator: This is the standard Lua way of getting the size of index tables i.e. ipairs() type of tables with numerical indices. To get the size of tables that use user defined keys instead of automatic indices (pairs() type) you need to use the function table.size() referenced above.

local test_table = { "value1", "value2", "value3", "value4" }
myTableSize = #test_table
-- This would return 4.
local myTable = { 1 = "hello", "key2" = "bye", "key3" = "time to go" }
table.size(myTable)
-- This would return 3.

table.unpickle

table.unpickle( t, tables, tcopy, pickled )
Internal function used by table.load() for deserialization.

table.update

table.union

table.union(...)
Returns a table that is the union of the provided tables. This is a union of key/value pairs. If two or more tables contain different values associated with the same key, that key in the returned table will contain a subtable containing all relevant values. See table.n_union() for a union of values. Note that the resulting table may not be reliably traversable with ipairs() due to the fact that it preserves keys. If there is a gap in numerical indices, ipairs() will cease traversal.
Examples
tableA = {
   [1] = 123,
   [2] = 456,
   ["test"] = "test",
}
---
tableB = {
   [1] = 23,
   [3] = 7,
   ["test2"] = function() return true end,
}
---
tableC = {
   [5] = "c",
}
---
table.union(tableA, tableB, tableC)
-- will return the following:
{
   [1] = {
      123,
      23,
   },
   [2] = 456,
   [3] = 7,
   [5] = "c",
   ["test"] = "test",
   ["test2"] = function() return true end,
}

UI Functions

appendBuffer

appendBuffer(name)
Pastes the previously copied rich text (including text formats like color etc.) into user window name.
See also: paste()
Parameters
  • name:
The name of the user window to paste into. Passed as a string.
Example
--selects and copies an entire line to user window named "Chat"
selectCurrentLine()
copy()
appendBuffer("Chat")

bg

bg([window, ]colorName)
Changes the background color of the text. Useful for highlighting text.
See Also: fg(), setBgColor()
Parameters
  • window:
The miniconsole to operate on - optional. If you'd like it to work on the main window, don't specify anything, or use main for the name.
  • colorName:
The name of the color to set the background to. Color Table
Example
--This would change the background color of the text on the current line to magenta
selectCurrentLine()
bg("magenta")
 
-- or echo text with a green background to a miniconsole
bg("my window", "green")
echo("my window", "some green text\n")

calcFontSize

calcFontSize(fontSize)
Used to calculate the number of pixels wide and high a character would be on a mini console at fontSize. As the primary intended usage is for calculating the needed dimensions of a miniConsole, it doesn't accept a font argument as the miniConsoles currently only work with the default font for the sake of portability.
Returns two numbers, width/height
See Also: setMiniConsoleFontSize(), getMainWindowSize()
Parameters
  • fontSize:
The font size you are wanting to calculate pixel sizes for. Passed as an integer number.
Example
--this snippet will calculate how wide and tall a miniconsole designed to hold 4 lines of text 20 characters wide 
--would need to be at 9 point font, and then changes miniconsole Chat to be that size
local width,height = calcFontSize(9)
width = width * 20
height = height * 4
resizeWindow("Chat", width, height)

cecho

cecho(window, text)
Echoes text that can be easily formatted with colour tags.
See Also: decho(), hecho()
Parameters
  • window:
Optional - the window name to echo to - can either be none or "main" for the main window, or the miniconsoles name.
  • text:
The text to display, with color names inside angle brackets <>, ie <red>. If you'd like to use a background color, put it after a double colon : - <:red>. You can use the <reset> tag to reset to the default color. You can select any from this list: Color Table
Example
cecho("Hi! This text is <red>red, <blue>blue, <green> and green.")
 
cecho("<:green>Green background on normal foreground. Here we add an <ivory>ivory foreground.")
 
cecho("<blue:yellow>Blue on yellow text!")
 
cecho("myinfo", "<green>All of this text is green in the myinfo miniconsole.")

cinsertText

cinsertText(window, text)
inserts text at the current cursor position, with the possibility for color tags.
See Also: cecho()
Parameters
  • window:
Optional - the window name to echo to - can either be none or "main" for the main window, or the miniconsoles name.
  • text:
The text to display, with color names inside angle brackets <>, ie <red>. If you'd like to use a background color, put it after a double colon : - <:red>. You can use the <reset> tag to reset to the default color. You can select any from this list: Color Table
Example
cinsertText("Hi! This text is <red>red, <blue>blue, <green> and green.")
 
cinsertText("<:green>Green background on normal foreground. Here we add an <ivory>ivory foreground.")
 
cinsertText("<blue:yellow>Blue on yellow text!")
 
cinsertText("myinfo", "<green>All of this text is green in the myinfo miniconsole.")

clearUserWindow

clearUserWindow(name)
Clears the window or miniconsole with the name given as argument.
Parameters
  • name:
The name of the user window to clear. Passed as a string.
Example
--This would clear a user window, or miniconsole with the name "Chat"
clearUserWindow("Chat")

clearWindow

clearWindow([optional name])
Clears the window or miniconsole with the name given as argument (removes all text from it). If you don't give it a name, it will clear the main window.
See also: clearUserWindow()
Parameters
  • name:
The name of the user window to clear. Passed as a string.
Example
--This would clear a label, user window, or miniconsole with the name "Chat"
clearWindow("Chat")
-- this can clear your whole main window - needs 2.0-test3+
clearWindow()

copy

copy([windowName])
Copies the current selection to the clipboard. This function operates on rich text, i. e. the selected text including all its format codes like colors, fonts etc. in the clipboard until it gets overwritten by another copy operation.
See Also: selectString(), selectCurrentLine()
Parameters
  • windowName:
Optional parameter to set the window from which to copy text.
Example
-- This script copies the current line on the main screen to a user window (mini console) named chat and gags the output on the main screen.
selectString( line )
copy()
appendBuffer("chat")
replace("This line has been moved to the chat window!")

createBuffer

createBuffer(name)
Creates a named buffer for formatted text, much like a miniconsole, but the buffer is not intended to be shown on the screen - use it for formatting text or storing formatted text.
Parameters
  • name:
The name of the buffer to create.
Example
--This creates a named buffer called "scratchpad"
createBuffer("scratchpad")

createButton

A similar function to createLabel() that is old and outdated - use createLabel() instead.

createConsole

createConsole(consoleName, fontSize, charsPerLine, numberOfLines, Xpos, Ypos)
Makes a new miniconsole. The background will be black, and the text color white.
Parameters
  • consoleName:
The name of your new miniconsole. Passed as a string.
  • fontSize:
The font size to use for the miniconsole. Passed as an integer number.
  • charsPerLine:
How many characters wide to make the miniconsole. Passed as an integer number.
  • numberOfLines:
How many lines high to make the miniconsole. Passed as an integer number.
  • Xpos:
X position of miniconsole. Measured in pixels, with 0 being the very left. Passed as an integer number.
  • Ypos:
Y position of miniconsole. Measured in pixels, with 0 being the very top. Passed as an integer number.
Example
-- this will create a console with the name of "myConsoleWindow", font size 8, 80 characters wide, 
-- 20 lines high, at coordinates 300x,400y
createConsole("myConsoleWindow", 8, 80, 20, 200, 400)

createGauge

createGauge(name, width, Xpos, Ypos, gaugeText, r, g, b)
createGauge(name, width, Xpos, Ypos, gaugeText, colorName)
Creates a gauge that you can use to express completion with. For example, you can use this as your healthbar or xpbar.
See also: moveGauge(), setGauge(), setGaugeText()
Parameters
  • name:
The name of the gauge. Must be unique, you can not have two or more gauges with the same name. Passed as a string.
  • width:
The width of the gauge, in pixels. Passed as an integer number.
  • height:
The height of the gauge, in pixels. Passed as an integer number.
  • Xpos:
X position of gauge. Measured in pixels, with 0 being the very left. Passed as an integer number.
  • Ypos:
Y position of gauge. Measured in pixels, with 0 being the very top. Passed as an integer number.
  • gaugeText:
Text to display on the gauge. Passed as a string, unless you do not wish to have any text, in which case you pass nil
  • r:
The red component of the gauge color. Passed as an integer number from 0 to 255
  • g:
The green component of the gauge color. Passed as an integer number from 0 to 255
  • b:
The blue component of the gauge color. Passed as an integer number from 0 to 255
  • colorName:
the name of color for the gauge. Passed as a string.
Example
-- This would make a gauge at that's 300px width, 20px in height, located at Xpos and Ypos and is green.
-- The second example is using the same names you'd use for something like [[fg]]() or [[bg]]().
createGauge("healthBar", 300, 20, 30, 300, nil, 0, 255, 0)
createGauge("healthBar", 300, 20, 30, 300, nil, "green")
 
 
-- If you wish to have some text on your label, you'll change the nil part and make it look like this:
createGauge("healthBar", 300, 20, 30, 300, "Now with some text", 0, 255, 0)
-- or
createGauge("healthBar", 300, 20, 30, 300, "Now with some text", "green")

Note Note: If you want to put text on the back of the gauge when it's low, use an echo with the <gauge name>_back.

echo("healthBar_back", "This is a test of putting text on the back of the gauge!")

createLabel

createLabel(name, Xpos, Ypos, width, height, fillBackground)
Creates a highly manipulable overlay which can take some css and html code for text formatting. Labels are clickable, and as such can be used as a sort of button. Labels are meant for small variable or prompt displays, messages, images, and the like. You should not use them for larger text displays or things which will be updated rapidly and in high volume, as they are much slower than miniconsoles.
Returns true or false.
See also: hideWindow(), showWindow(), resizeWindow(), setLabelClickCallback(), setTextFormat(), setTextFormat(), setBackgroundColor(), getMainWindowSize(), calcFontSize()
Parameters
  • name:
The name of the label. Must be unique, you can not have two or more labels with the same name. Passed as a string.
  • Xpos:
X position of the label. Measured in pixels, with 0 being the very left. Passed as an integer number.
  • Ypos:
Y position of the label. Measured in pixels, with 0 being the very top. Passed as an integer number.
  • width:
The width of the label, in pixels. Passed as an integer number.
  • height:
The height of the label, in pixels. Passed as an integer number.
  • fillBackground:
Whether or not to display the background. Passed as either 1 or 0. 1 will display the background color, 0 will not.
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 non-transparent) the background text can still be read through. The message box will disappear after 2.3 seconds.
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", 150,100,100,200);
echo("messageBox", [[<p style="font-size:35px"><b><center><font color="red">You are under attack!</font></center></b></p>]] );
showWindow("messageBox");
tempTimer(2.3, [[hideWindow("messageBox")]] ) -- close the warning message box after 2.3 seconds

createMiniConsole

createMiniConsole(name, 0,0,0,0)
Opens a miniconsole window inside the main window of Mudlet. This is the ideal fast colored text display for everything that requires a bit more text, such as status screens, chat windows, etc. Unlike labels, you cannot have transparency in them.
You can use clearWindow() / moveCursor() and other functions for this window for custom printing as well as copy & paste functions for colored text copies from the main window. setWindowWrap() will allow you to set word wrapping, and move the main window to make room for miniconsole windows on your screen (if you want to do this as you can also layer mini console and label windows) see setBorderTop(), setBorderColor() functions.
Returns true or false.
See also: createLabel(), hideWindow(), showWindow(), resizeWindow(), setTextFormat(), moveWindow(), setMiniConsoleFontSize(), handleWindowResizeEvent(), setBorderTop(), setWindowWrap(), getMainWindowSize(), calcFontSize(), calcFontSize()
Parameters
  • name:
The name of the miniconsole. Must be unique, you can not have two or more miniconsoles with the same name. Passed as a string.
  • 0,0,0,0:
Parameters to set set the window size and location - however it's best to set them via moveWindow() and resizeWindow(), as createMiniConsole() will only set them once.
Example
--This script would create a mini text console called "sys" and write with yellow foreground color and blue background color 
--"Hello World".
 
 
-- set up the small system message window in the top right corner
-- determine the size of your screen
WindowWidth = 0;
WindowHeight = 0;
WindowWidth, WindowHeight = getMainWindowSize();
 
createMiniConsole("sys", 0,0,0,0)
moveWindow("sys", WindowWidth-650,0)
resizeWindow("sys", 650,300)
setBackgroundColor("sys",85,55,0,255)
setMiniConsoleFontSize("sys", 8)
-- wrap lines in window "sys" at 40 characters per line
setWindowWrap("sys", 40)
setMiniConsoleFontSize("sys", 10)
 
-- set default font colors and font style for window "sys"
setTextFormat("sys",0,35,255,50,50,50,0,0,0)
 
echo("sys","Hello world!")

decho

decho ([name of console,] text)
Color changes can be made using the format <FR,FG,FB:BR,BG,BB> where each field is a number from 0 to 255. The background portion can be omitted using <FR,FG,FB> or the foreground portion can be omitted using <:BR,BG,BB>. Arguments 2 and 3 set the default fore and background colors for the string using the same format as is used within the string, sans angle brackets, e.g. decho("<50,50,0:0,255,0>test").
Parameters
  • text:
The text that you’d like to echo with embedded color tags. Tags take the RGB values only, see below for an explanation.
  • name of console
Optional name of the console to echo to. Defaults to main.
Example
decho("<50,50,0:0,255,0>test")
 
decho("miniconsolename", "<50,50,0:0,255,0>test")

deleteLine

deleteLine()
Deletes the current line under the user cursor. This is a high speed gagging tool and is very good at this task, but is only meant to be use when a line should be omitted entirely in the output. If you echo() to that line it will not be shown, and lines deleted with deleteLine() are simply no longer rendered.
See Also: replace(), wrapLine()

Note Note: you do not need to put anything between () - it just deletes the line it is used on.

Note Note: for replacing text, replace() is the proper option; doing the following: selectCurrentLine(); replace(""); cecho("new line!\n") is better.

Example
-- deletes the line - just put this command into the big script box. Keep the case the same -
-- it has to be deleteLine(), not Deleteline(), deleteline() or anything else
deleteLine()
 
--This example creates a temporary line trigger to test if the next line is a prompt, and if so gags it entirely.
--This can be useful for keeping a pile of prompts from forming if you're gagging chat channels in the main window
--Note: isPrompt() only works on servers which send a GA signal with their prompt.
tempLineTrigger(1, 1, [[if isPrompt() then deleteLine() end]])
 
-- example of deleting multiple lines:
deleteLine()                            -- delete the current line
moveCursor(0,getLineNumber()-1)  -- move the cursor back one line
deleteLine()                            -- delete the previous line now

deselect

deselect([optional window name])
This is used to clear the current selection (to no longer have anything selected). Should be used after changing the formatting of text, to keep from accidentally changing the text again later with another formatting call.
Parameters
  • name:
The name of the buffer/miniConsole to stop having anything selected in. This is an optional argument, if name is not provided the main window will have its selection cleared.
Example
--This will change the background on an entire line in the main window to red, and then properly clear the selection to keep further 
--changes from effecting this line as well.
selectCurrentLine()
bg("red")
deselect()

echoLink

echoLink([windowName], text, command, hint, [bool use_current_format or defaultLinkFormat])
Echos a piece of text as a clickable link, at the end of the current selected line - similar to echo().
Parameters
  • text:
text to display in the echo. Same as a normal echo().
  • command:
lua code to do when the link is clicked.
  • hint:
text for the tooltip to be displayed when the mouse is over the link.
  • window:
if true, then the link will use the current selection style (colors, underline, etc). If missing or false, it will use the default link style - blue on black underlined text.
Example
-- echo a link named 'press me!' that'll send the 'hi' command to the game
echoLink("press me!", [[send("hi")]], "This is a tooltip")
 
-- do the same, but send this link to a miniConsole
echoLink("my miniConsole", "press me!", [[send("hi")]], "This is a tooltip")

echoUserWindow

echoUserWindow(windowName)
This function will print text to both mini console windows, dock windows and labels. It is outdated however - echo() instead.

echoPopup

echoPopup([window], text, {commands}, {hints}, [current or default format])
Creates text with a left-clickable link, and a right-click menu for more options at the end of the current line, like echo. The added text, upon being left-clicked, will do the first command in the list. Upon being right-clicked, it'll display a menu with all possible commands. The menu will be populated with hints, one for each line.
Parameters
  • window:
Optional - the window to echo to - use either main or omit for the main window, or the miniconsoles name otherwise.
  • name:
the name of the console to operate on. If not using this in a miniConsole, use "main" as the name.
  • {lua code}:
a table of lua code strings to do. ie,
{[[send("hello")]], [[echo("hi!"]]}
  • {hints}:
a table of strings which will be shown on the popup and right-click menu. ie,
{"send the hi command", "echo hi to yourself"}
  • current or default format:
a boolean value for using either the current formatting options (colour, underline, italic) or the link default (blue underline).
Example
-- Create some text as a clickable with a popup menu:
echoPopup("activities to do", {[[send "sleep"]], [[send "sit"]], [[send "stand"]]}, {"sleep", "sit", "stand"})

fg

fg([window, ]colorName)
If used on a selection, sets the foreground color to colorName - otherwise, it will set the color of the next text-inserting calls (echo(), insertText, echoLink(), and others)
See Also: bg(), setBgColor()
Parameters
  • window:
The MiniConsole to operate on - optional. If you'd like it to work on the main window, don't specify anything.
  • colorName:
The name of the color to set the foreground to - list of possible names: Color Table
Example
--This would change the color of the text on the current line to green
selectCurrentLine()
fg("green")
resetFormat()
 
--This will echo red, green, blue in their respective colors
fg("red")
echo("red ")
fg("green")
echo("green ")
fg("blue")
echo("blue ")
resetFormat()
 
-- example of working on a miniconsole
fg("my console", "red")
echo("my console", "red text")

getBgColor

getBgColor(windowName)
This function returns the rgb values of the background color of the first character of the current selection on mini console (window) windowName. If windowName is omitted Mudlet will use the main screen.
Parameters
  • windowName:
A window to operate on - either a miniconsole or the main window.
Example
local r,g,b;
selectString("troll",1)
r,g,b = getBgColor()
if r == 255 and g == 0 and b == 0 then
    echo("HELP! troll is highlighted in red letters, the monster is aggressive!\n");
end

getColorWildcard

getColorWildcard(ansi color number)
This function, given an ANSI color number (list), will return all strings on the current line that match it.
Parameters
  • ansi color number:
A color number (list) to match.
Example
-- we can run this script on a line that has the players name coloured differently to easily capture it from 
-- anywhere on the line
local match = getColorWildcard(14)
 
if match then
  echo("\nFound "..match.."!")
else
  echo("\nDidn't find anyone.")
end

getColumnNumber

getColumnNumber([window])
Gets the absolute column number of the current user cursor.
Parameters
  • window:
The minoconsole to operate on - optional. If you'd like it to work on the main window, don't specify anything.

Note Note: the window argument will be available in a release of Mudlet later than 2.1.

Example
HelloWorld = Geyser.MiniConsole:new({
  name="HelloWorld",
  x="70%", y="50%",
  width="30%", height="50%",
})
 
HelloWorld:echo("hello!\n")
HelloWorld:echo("hello!\n")
HelloWorld:echo("hello!\n")
 
moveCursor("HelloWorld", 3, getLastLineNumber("HelloWorld"))
-- should say 3, because we moved the cursor in the HellWorld window to the 3rd position in the line
print("getColumnNumber: "..tostring(getColumnNumber("HelloWorld")))
 
moveCursor("HelloWorld", 1, getLastLineNumber("HelloWorld"))
-- should say 3, because we moved the cursor in the HellWorld window to the 1st position in the line
print("getColumnNumber: "..tostring(getColumnNumber("HelloWorld")))

getCurrentLine

getCurrentLine()
Returns the content of the current line under the user cursor in the buffer. The Lua variable line holds the content of getCurrentLine() before any triggers have been run on this line. When triggers change the content of the buffer, the variable line will not be adjusted and thus hold an outdated string. line = getCurrentLine() will update line to the real content of the current buffer. This is important if you want to copy the current line after it has been changed by some triggers. selectString( line,1 ) will return false and won't select anything because line no longer equals getCurrentLine(). Consequently, selectString( getCurrentLine(), 1 ) is what you need.
Example
print("Currently selected line: "..getCurrentLine())

getFgColor

getFgColor(windowName)
This function returns the rgb values of the color of the first character of the current selection on mini console (window) windowName. If windowName is omitted Mudlet will use the main screen.
Parameters
  • windowName:
A window to operate on - either a miniconsole or the main window.
Example
local r,g,b;
selectString("troll",1)
r,g,b = getFgColor()
if r == 255 and g == 0 and b == 0 then
    echo("HELP! troll is written in red letters, the monster is aggressive!\n");
end

getLastLineNumber

getLastLineNumber(window)
Returns the latest line's number in the main window or the miniconsole. This could be different from getLineNumber() if the cursor was moved around.
Parameters
  • window:
The window to use - either use main for the main window, or the miniconsoles name.
Example
-- get the latest line's # in the buffer
local latestline = getLastLineNumber("main")


getLineCount

getLineCount()
Gets the absolute amount of lines in the current console buffer
Parameters
None
Example

Need example

getLines

getLines(from_line_number, to_line_number)
Returns a section of the content of the screen text buffer. Returns a Lua table with the content of the lines on a per line basis. The form value is result = {relative_linenumber = line}.
Absolute line numbers are used.
Parameters
  • from_line_number:
First line number
  • to_line_number:
End line number
Example
-- retrieve & echo the last line: 
echo(getLines(getLineNumber()-1, getLineNumber())[1])
-- find out which server and port you are connected to (as per Mudlet settings dialog):
local t = getLines(0, getLineNumber())
 
local server, port
 
for i = 1, #t do
  local s, p = t[i]:match("looking up the IP address of server:(.-):(%d+)")
  if s then server, port = s, p break end
end
 
display(server)
display(port)

getLineNumber

getLineNumber([window])
Returns the absolute line number of the current user cursor (the y position). The cursor by default is on the current line the triggers are processing - which you can move around with moveCursor() and moveCursorEnd(). This function can come in handy in combination when using with moveCursor() and getLines().
Parameters
  • window:
The miniconsole to operate on - optional. If you'd like it to work on the main window, don't specify anything.

Note Note: the window argument will be available in a release of Mudlet later than 2.1.

Example
-- use getLines() in conjuction with getLineNumber() to check if the previous line has a certain word
if getLines(getLineNumber()-1, getLineNumber())[1]:find("attacks") then echo("previous line had the word 'attacks' in it!\n") end
 
-- check how many lines you've got in your miniconsole after echoing some text.
-- Note the use of moveCursorEnd() to update getLineNumber()'s output
HelloWorld = Geyser.MiniConsole:new({
  name="HelloWorld",
  x="70%", y="50%",
  width="30%", height="50%",
})
 
print(getLineNumber("HelloWorld"))
 
HelloWorld:echo("hello!\n")
HelloWorld:echo("hello!\n")
HelloWorld:echo("hello!\n")
 
-- update the cursors position, as it seems to be necessary to do
moveCursorEnd("HelloWorld")
print(getLineNumber("HelloWorld"))

getMainConsoleWidth

getMainConsoleWidth()
Returns a single number; the width of the main console (MuD output) in pixels.
Parameters
None
Example
-- Save width of the main console to a variable for future use.
consoleWidth = getMainConsoleWidth()

hasFocus

hasFocus()
Returns true or false depending if Mudlet's main window is currently in focus (ie, the user isn't focused on another window, like a browser). This can be useful for determining whenever your script should call for attention or not, for example.
Parameters
None
Example
if attacked and not hasFocus() then
  runaway()
else
  fight()
end

getMainWindowSize

getMainWindowSize()
Returns two numbers, the width and height in pixels.
Parameters
None
Example
--this will get the size of your main mudlet window and save them 
--into the variables mainHeight and mainWidth
mainWidth, mainHeight = getMainWindowSize()

getStopWatchTime

getStopWatchTimer(watchID)
Returns the time (milliseconds based) in form of 0.058 (= clock ran for 58 milliseconds before it was stopped). Please note that after the stopwatch is stopped, retrieving the time will not work - it's only valid while it is running.
See also: createStopWatch()
Returns a number
Parameters
  • watchID
The ID number of the watch.
Example
-- an example of showing the time left on the stopwatch
teststopwatch = teststopwatch or createStopWatch()
startStopWatch(teststopwatch)
echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))
tempTimer(1, [[echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))]])
tempTimer(2, [[echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))]])
stopStopWatch(teststopwatch)

handleWindowResizeEvent

handleWindowResizeEvent()
(depreciated) This function is depreciated and should not be used; it's only documented here for historical reference - use the sysWindowResizeEvent event instead.

The standard implementation of this function does nothing. However, this function gets called whenever the main window is being manually resized. You can overwrite this function in your own scripts to handle window resize events yourself and e. g. adjust the screen position and size of your mini console windows, labels or other relevant GUI elements in your scripts that depend on the size of the main Window. To override this function you can simply put a function with the same name in one of your scripts thus overwriting the original empty implementation of this.

Parameters
None
Example
function handleWindowResizeEvent()
   -- determine the size of your screen
   WindowWidth=0;
   WindowHeight=0;
   WindowWidth, WindowHeight = getMainWindowSize();
 
   -- move mini console "sys" to the far right side of the screen whenever the screen gets resized
   moveWindow("sys",WindowWidth-300,0)
end

hasFocus

hasFocus()
Returns true or false depending on if the main Mudlet window is in focus. By focus, it means that the window is selected and you can type in the input line and etc. Not in focus means that the window isn’t selected, some other window is currently in focus.
Parameters
None
Example

Need example

hecho

hecho(window, text)
Echoes text that can be easily formatted with colour tags in the hexadecimal format.
See Also: decho(), cecho()
Parameters
  • window:
Optional - the window name to echo to - can either be none or "main" for the main window, or the miniconsoles name.
  • text:
The text to display, with color changes made within the string using the format |cFRFGFB,BRBGBB where FR is the foreground red value, FG is the foreground green value, FB is the foreground blue value, BR is the background red value, etc., BRBGBB is optional. |r can be used within the string to reset the colors to default.
Example
hecho("|ca00040black!")

hideToolBar

hideToolBar(name)
Hides the toolbar with the given name name and makes it disappear. If all toolbars of a tool bar area (top, left, right) are hidden, the entire tool bar area disappears automatically.
Parameters
  • name:
name of the button group to display
Example
hideToolBar("my offensive buttons")

hideWindow

hideWindow(name)
This function hides a mini console label. To show it again, use showWindow().
See also: createMiniConsole(), createLabel()
Parameters
None
Example

Need example

insertLink

insertLink([windowName], text, command, hint, [bool use_current_format or defaultLinkFormat])
Inserts a piece of text as a clickable link at the current cursor position - similar to insertText().
Parameters
  • text:
text to display in the echo. Same as a normal echo().
  • command:
lua code to do when the link is clicked.
  • hint:
text for the tooltip to be displayed when the mouse is over the link.
  • window:
if true, then the link will use the current selection style (colors, underline, etc). If missing or false, it will use the default link style - blue on black underlined text.
Example
-- link with the default blue on white colors
insertLink("hey, click me!", [[echo("you clicked me!\n")]], "Click me popup")
 
-- use current cursor colors by adding true at the end
fg("red")
insertLink("hey, click me!", [[echo("you clicked me!\n")]], "Click me popup", true)
resetFormat()

insertPopup

insertPopup([windowName], text, {commands}, {hints}, [current or default format])
Creates text with a left-clickable link, and a right-click menu for more options exactly where the cursor position is, similar to insertText(). The inserted text, upon being left-clicked, will do the first command in the list. Upon being right-clicked, it'll display a menu with all possible commands. The menu will be populated with hints, one for each line.
Parameters
  • window:
Optional - the window to echo to - use either main or omit for the main window, or the miniconsoles name otherwise.
  • name:
the name of the console to operate on. If not using this in a miniConsole, use "main" as the name.
  • {lua code}:
a table of lua code strings to do. ie,
{[[send("hello")]], [[echo("hi!"]]}
.
  • {hints}:
a table of strings which will be shown on the popup and right-click menu. ie,
{"send the hi command", "echo hi to yourself"}
.
  • current or default format:
a boolean value for using either the current formatting options (colour, underline, italic) or the link default (blue underline).
Example
-- Create some text as a clickable with a popup menu:
insertPopup("activities to do", {[[send "sleep"]], [[send "sit"]], [[send "stand"]]}, {"sleep", "sit", "stand"})

insertText

insertText([optional windowName], text)
Inserts text at cursor postion in window - unlike echo(), which inserts the text at the end of the last line in the buffer (typically the one being processed by the triggers). You can use moveCursor() to move the cursor into position first.
insertHTML() also does the same thing as insertText, if you ever come across it.
See also: cinsertText()
Parameters
  • window:
The window to insert the text to.
  • text:
The text you will insert into the current cursor position.
Example
-- move the cursor to the end of the previous line and insert some text
 
-- move to the previous line
moveCursor(0, getLineNumber()-1)
-- move the end the of the previous line
moveCursor(#getCurrentLine(), getLineNumber())
 
fg("dark_slate_gray")
insertText(' <- that looks nice.')
 
deselect()
resetFormat()
moveCursorEnd()

ioprint

ioprint(text, some more text, ...)
Prints text to the to the stdout. This is only available if you launched Mudlet from cmd.exe on Windows, from the terminal on Mac, or from the terminal on a Linux OS (launch the terminal program, type mudlet and press enter).

Similar to echo(), but does not require a "\n" at the end for a newline and can print several items given to it. It cannot print whole tables. This function works similarly to the print() you will see in guides for Lua.

This function is useful in working out potential crashing problems with Mudlet due to your scripts - as you will still see whatever it printed when Mudlet crashes.

Parameters
  • text:
The information you want to display.
Example
ioprint("hi!")
ioprint(1,2,3)
ioprint(myvariable, someothervariable, yetanothervariable)

isAnsiBgColor

isAnsiBgColor(ansiBgColorCode)
This function tests if the first character of the current selection has the background color specified by ansiBgColorCode.
Parameters
  • ansiBgColorCode:
A color code to test for, possible codes are:
0 = default text color
1 = light black
2 = dark black
3 = light red
4 = dark red
5 = light green
6 = dark green
7 = light yellow
8 = dark yellow
9 = light blue
10 = dark blue
11 = light magenta
12 = dark magenta
13 = light cyan
14 = dark cyan
15 = light white
16 = dark white
Example
selectString( matches[1], 1 )
if isAnsiBgColor( 5 ) then
    bg("red");
    resetFormat();
    echo("yes, the background of the text is light green")
else
    echo( "no sorry, some other backgroundground color" )
end

Note Note: matches[1] holds the matched trigger pattern - even in substring, exact match, begin of line substring trigger patterns or even color triggers that do not know about the concept of capture groups. Consequently, you can always test if the text that has fired the trigger has a certain color and react accordingly. This function is faster than using getFgColor() and then handling the color comparison in Lua.

isAnsiFgColor

isAnsiFgColor(ansiFgColorCode)
This function tests if the first character of the current selection has the foreground color specified by ansiFgColorCode.
Parameters
  • ansiFgColorCode:
A color code to test for, possible codes are:
0 = default text color
1 = light black
2 = dark black
3 = light red
4 = dark red
5 = light green
6 = dark green
7 = light yellow
8 = dark yellow
9 = light blue
10 = dark blue
11 = light magenta
12 = dark magenta
13 = light cyan
14 = dark cyan
15 = light white
16 = dark white
Example
selectString( matches[1], 1 )
if isAnsiFgColor( 5 ) then
    bg("red");
    resetFormat();
    echo("yes, the text is light green")
else
    echo( "no sorry, some other foreground color" )
end

Note Note: matches[1] holds the matched trigger pattern - even in substring, exact match, begin of line substring trigger patterns or even color triggers that do not know about the concept of capture groups. Consequently, you can always test if the text that has fired the trigger has a certain color and react accordingly. This function is faster than using getFgColor() and then handling the color comparison in Lua.

moveCursor

moveCursor([optional windowName], x, y)
Moves the user cursor of the window windowName, or the main window, to the absolute point (x,y). This function returns false if such a move is impossible e.g. the coordinates don’t exist. To determine the correct coordinates use getLineNumber(), getColumnNumber() and getLastLineNumber(). The trigger engine will always place the user cursor at the beginning of the current line before the script is run. If you omit the windowName argument, the main screen will be used.
Returns true or false depending on if the cursor was moved to a valid position. Check this before doing further cursor operations - because things like deleteLine() might invalidate this.
Parameters
  • windowName:
The window you are going to move the cursor in.
  • x:
The horizontal axis in the window - that is, the letter position within the line.
  • y:
The vertical axis in the window - that is, the line number.
Example
-- move cursor to the start of the previous line and insert -<(
-- the first 0 means we want the cursor right at the start of the line,
-- and getLineNumber()-1 means we want the cursor on the current line# - 1 which
-- equals to the previous line
moveCursor(0, getLineNumber()-1)
insertText("-<(")
 
-- now we move the cursor at the end of the previous line. Because the 
-- cursor is on the previous line already, we can use #getCurrentLine()
-- to see how long it is. We also just do getLineNumber() because getLineNumber()
-- returns the current line # the cursor is on
moveCursor(#getCurrentLine(), getLineNumber())
insertText(")>-")
 
-- finally, reset it to the end where it was after our shenaningans - other scripts
-- could expect the cursor to be at the end
moveCursorEnd()
-- a more complicated example showing how to work with Mudlet functions
 
-- set up the small system message window in the top right corner
-- determine the size of your screen
local WindowWidth, WindowHeight = getMainWindowSize()
 
-- define a mini console named "sys" and set its background color
createMiniConsole("sys",WindowWidth-650,0,650,300)
setBackgroundColor("sys",85,55,0,255)
 
-- you *must* set the font size, otherwise mini windows will not work properly
setMiniConsoleFontSize("sys", 12)
-- wrap lines in window "sys" at 65 characters per line
setWindowWrap("sys", 60)
-- set default font colors and font style for window "sys"
setTextFormat("sys",0,35,255,50,50,50,0,0,0)
-- clear the window
clearUserWindow("sys")
 
moveCursorEnd("sys")
setFgColor("sys", 10,10,0)
setBgColor("sys", 0,0,255)
echo("sys", "test1---line1\n<this line is to be deleted>\n<this line is to be deleted also>\n")
echo("sys", "test1---line2\n")
echo("sys", "test1---line3\n")
setTextFormat("sys",158,0,255,255,0,255,0,0,0);
--setFgColor("sys",255,0,0);
echo("sys", "test1---line4\n")
echo("sys", "test1---line5\n")
moveCursor("sys", 1,1)
 
-- deleting lines 2+3
deleteLine("sys")
deleteLine("sys")
 
-- inserting a line at pos 5,2
moveCursor("sys", 5,2)
setFgColor("sys", 100,100,0)
setBgColor("sys", 255,100,0)
insertText("sys","############## line inserted at pos 5/2 ##############")
 
-- inserting a line at pos 0,0
moveCursor("sys", 0,0)
selectCurrentLine("sys")
setFgColor("sys", 255,155,255)
setBold( "sys", true );
setUnderline( "sys", true )
setItalics( "sys", true )
insertText("sys", "------- line inserted at: 0/0 -----\n")
 
setBold( "sys", true )
setUnderline( "sys", false )
setItalics( "sys", false )
setFgColor("sys", 255,100,0)
setBgColor("sys", 155,155,0)
echo("sys", "*** This is the end. ***\n")

moveCursorEnd

moveCursorEnd( windowName )
Moves the cursor to the end of the buffer. "main" is the name of the main window, otherwise use the name of your user window.
See Also: moveCursor()
Returns true or false
Parameters
  • windowName:
The name of your user window.
Example

Need example

moveGauge

moveGauge(gaugeName, newX, newY)
Moves a gauge created with createGauge to the new x,y coordinates. Remember the coordinates are relative to the top-left corner of the output window.
Parameters
  • gaugeName:
The name of your gauge
  • newX:
The horizontal pixel location
  • newY:
The vertical pixel location
Example
-- This would move the health bar gauge to the location 1200, 400
moveGauge("healthBar", 1200, 400)

moveWindow

moveWindow( name, x, y )
This function moves window name to the given x/y coordinate. The main screen cannot be moved. Instead you’ll have to set appropriate border values → preferences to move the main screen e.g. to make room for chat or information mini consoles, or other GUI elements. In the future moveWindow() will set the border values automatically if the name parameter is omitted.
See Also: createMiniConsole(), createLabel(), handleWindowResizeEvent(), resizeWindow(), setBorderTop()
Parameters
  • name:
The name of your winow
  • newX:
The horizontal pixel location
  • newY:
The vertical pixel location

openUserWindow

openUserWindow(name)
Opens a user dockable console window for user output e.g. statistics, chat etc. If a window of such a name already exists, nothing happens. You can move these windows, dock them, make them into notebook tabs or float them. Note that they do currently have a bug in a sense that they will inherit your main windows borders. The windows position cannot be adjusting via scripting yet at the moment, and the layout won't be remembered next time Mudlet is open.
Parameters
  • name: The name of your window
Examples
openUserWindow("My floating window")
cecho("My floating window", "<red>hello <blue>bob!")

paste

paste(windowName)
Pastes the previously copied text including all format codes like color, font etc. at the current user cursor position. The copy() and paste() functions can be used to copy formated text from the main window to a user window without losing colors e. g. for chat windows, map windows etc.
Parameters
  • windowName:
The name of your window

pasteUserWindow

pasteUserWindow(windowName)
Need description here
Parameters
  • windowName:
The name of your window

prefix

prefix(text)
Prefixes text at the beginning of the current line when used in a trigger.
Parameters
  • text:
The information you want to prefix
Example
-- Prefix the hours, minutes and seconds onto our prompt even though Mudlet has a button for that
prefix(os.date("%H:%M:%S "))

print

print(text, some more text, ...)
Prints text to the main window. Similar to echo(), but does not require a "\n" at the end for a newline and can print several items given to it. It cannot print whole tables - use display() for those. This function works similarly to the print() you will see in guides for Lua.
Parameters
  • text:
The information you want to display.
Example
print("hi!")
print(1,2,3)
print(myvariable, someothervariable, yetanothervariable)

replace

replace([windowName,] newtext)
Replaces the currently selected text with the new text. To select text, use selectString(), selectSection() or a similar function.

Note Note: If you’d like to delete/gag the whole line, use deleteLine() instead.

Note Note: replace() does not preserve existing colours by default - however it's easy to make it so, see example below.

Note Note: when used outside of a trigger context (for example, in a timer instead of a trigger), replace() won't trigger the screen to refresh. Instead, use replace("") and insertText("new text") as insertText() does.

Parameters
  • windowName: optional name of window (a miniconsole)
  • with: the new text to display.
Example
-- replace word "troll" with "cute trolly"
selectString("troll",1)
replace("cute trolly")
 
-- replace the whole line
selectCurrentLine()
replace("Out with the old, in with the new!")
 
-- if you'd like to keep the original colouring instead of applying your own, you can do this:
if selectString("There", 1) ~= -1 then
  setBgColor(getBgColor())
  setFgColor(getFgColor())
  replace("Here")
end

replaceAll

replaceAll( what, with )
Replaces all occurrences of what in the current line with with.
Parameters
  • what: the text to replace
  • with: the new text to have in place
Examples
-- replace all occurrences of the word "south" in the line with "north"
replaceAll("south", "north")
-- replace all occurrences of the text that the variable "target" has
replaceAll(target, "The Bad Guy")

resizeWindow

resizeWindow(name,width,height)
Resizes a mini console or label
See also: createMiniConsole(), createLabel(), handleWindowResizeEvent(), resizeWindow(), setBorderTop()

selectCaptureGroup

selectCaptureGroup(groupNumber)
Selects the content of the capture group number in your Perl regular expression (from matches[]). It does not work with multimatches.
Example
Perl Reqular expression e.g. "you have (\d+) Euro".
--If you want to color the amount of money you have green you do: 
 
selectCaptureGroup(1)
setFgColor(0,255,0)

selectSection

selectSection(from, how long)
Selects the specified parts of the line starting from the left and extending to the right for however how long. The line starts from 0.
Returns true if the selection was successful, and false if the line wasn't actually long enough or the selection couldn't be done in general.
Example
-- select and colour the first character in the line red
if selectSection(0,1) then fg("red") end
 
-- select and colour the second character green (start selecting from the first character, and select 1 character)
if selectSection(1,1) then fg("green") end
 
-- select and colour three character after the first two grey (start selecting from the 2nd character for 3 characters long)
if selectSection(2,3) then fg("grey") end

selectString

selectString( [windowName], text, number_of_match )
Selects a substring from the line where the user cursor is currently positioned - allowing you to edit selected text (apply colour, make it be a link, copy to other windows or other things).

You can move the user cursor with moveCursor(). When a new line arrives from the MUD, the user cursor is positioned at the beginning of the line. However, if one of your trigger scripts moves the cursor around you need to take care of the cursor position yourself and make sure that the cursor is in the correct line if you want to call one of the select functions. To deselect text, see deselect().

Parameters
  • windowName:
Optional parameter to set the window in which to select text.
  • text:
The text to select. It is matched as a substring match (so the text anywhere within the line will get selected).
  • number_of_match:
The occurrence of text on the line that you'd like to select. For example, if the line was "Bob and Bob", 1 would select the first Bob, and 2 would select the second Bob.
Returns position in line or -1 on error (text not found in line)

Note Note: To prevent working on random text if your selection didn't actually select anything, check the -1 return code before doing changes:

if selectString( "big monster", 1 ) > -1 then fg("red") end

setBgColor

setBgColor([windowName], r,g,b )
Sets the current text background color in the main window unless windowName parameter given. If you have selected text prior to this call, the selection will be highlighted otherwise the current text background color will be changed. If you set a foreground or background color, the color will be used until you call resetFormat() on all further print commands.

See also: cecho()

Parameters
  • windowName:
Optional parameter set the current text background color in windowname given.
  • r:
The red component of the gauge color. Passed as an integer number from 0 to 255
  • g:
The green component of the gauge color. Passed as an integer number from 0 to 255
  • b:
The blue component of the gauge color. Passed as an integer number from 0 to 255
Example
--highlights the first occurrence of the string "Tom" in the current line with a red background color.
selectString( "Tom", 1 )
setBgColor( 255,0,0 )
--prints "Hello" on red background and "You" on blue.
setBgColor(255,0,0)
echo("Hello")
setBgColor(0,0,255)
echo(" You!")
resetFormat()

setBold

setBold(windowName, boolean)
Sets the current text font to bold (true) or non-bold (false) mode. If the windowName parameters omitted, the main screen will be used. If you've got text currently selected in the Mudlet buffer, then the selection will be bolded. Any text you add after with echo() or insertText() will be bolded until you use resetFormat().
  • windowName:
Optional parameter set the current text background color in windowname given.
  • boolean:
A true or false that enables or disables bolding of text
Example
-- enable bold formatting
setBold(true)
-- the following echo will be bolded
echo("hi")
-- turns off bolding, italics, underlines and colouring. It's good practice to clean up after you're done with the formatting, so other your formatting doesn't "bleed" into other echoes.
resetFormat()

setFgColor

setFgColor([windowName],r, g, b)
Sets the current text foreground color in the main window unless windowName parameter given.
  • windowName:
Optional parameter set the current text background color in windowname given.
  • r:
The red component of the gauge color. Passed as an integer number from 0 to 255
  • g:
The green component of the gauge color. Passed as an integer number from 0 to 255
  • b:
The blue component of the gauge color. Passed as an integer number from 0 to 255
Example
--highlights the first occurrence of the string "Tom" in the current line with a red foreground color.
selectString( "Tom", 1 )
setFgColor( 255,0,0 )

setGauge

setGauge(gaugeName, currentValue, maxValue, gaugeText)
Use this function when you want to change the gauges look according to your values. Typical usage would be in a prompt with your current health or whatever value, and throw in some variables instead of the numbers.
Example
--Change the looks of the gauge named healthBar and make it 
--fill to half of its capacity. The height is always remembered.
setGauge("healthBar", 200, 400)
--If you wish to change the text on your gauge, you’d do the following:
setGauge("healthBar", 200, 400, "some text")

setItalics

setItalics(windowName, bool)
Sets the current text font to italics/non-italics mode. If the windowName parameters omitted, the main screen will be used.

setMiniConsoleFontSize

setMiniConsoleFontSize(name, fontSize)

Sets the font size of the mini console. see also: createMiniConsole(), createLabel()

setTextFormat

setTextFormat(windowName, r1, g1, b1, r2, g2, b2, bold, underline, italics)
Sets current text format of window windowName: foreground color(r1,g1,b1), background color(r2,g2,b2), bold(1/0), underline(1/0), italics(1/0) A more convenient way to control the text format in a mini console is to use setFgColor( windowName, r,g,b ), setBold( windowName, true ), setItalics( windowName, true ), setUnderline( windowName, true ) etc. → createMiniConsole, setBold, setBgColor, setFgColor, setItalics, setUnderline
Example
--This script would create a mini text console and write with yellow foreground color and blue background color "This is a test".
createMiniConsole( "con1", 0,0,300,100);
setTextFormat("con1",0,0,255,255,255,0,1,1,1);
echo("con1","This is a test")

setUnderline

setUnderline(windowName, bool)
Sets the current text font to underline/non-underline mode. If the windowName parameters omitted, the main screen will be used.

setWindowWrap

setWindowWrap(windowName, wrapAt)
sets at what position in the line the console or miniconsole will start word wrap

showCaptureGroups

showCaptureGroups()
Lua debug function that highlights in random coolors all capture groups in your trigger regex on the screen. This is very handy if you make complex regex and want to see what really matches in the text. This function is defined in LuaGlobal.lua.
Example
Make a trigger with the regex (\w+) and call this function in a trigger. All words in the text will be highlighted in random colors.

showMultimatches

showMultimatches()
Lua helper function to show you what the table multimatches[n][m] contains. This is very useful when debugging multiline triggers - just doing showMultimatches() in your script will make it give the info.

showWindow

showWindow(name)
Makes a hidden window (label or miniconsole) be shown again.
See also: hideWindow()

suffix

suffix(text)
Suffixes text at the end of the current line. This is similar to echo(), which also suffixes text at the end of the line, but different - echo() makes sure to do it on the last line in the buffer, while suffix does it on the line the cursor is currently on.
See also: prefix(), echo()

replaceWildcard

replaceWildcard(which, replacement)
Replaces the given wildcard (as a number) with the given text. Equivalent to doing:
selectString(matches[2], 1)
replace("text")
Parameters
  • which:
Wildcard to replace.
  • replacement:
Text to replace the wildcard with.
Example
replaceWildcard(2, "hello") -- on a perl regex trigger of ^You wave (goodbye)\.$, it will make it seem like you waved hello

resetFormat

resetFormat()
Resets the colour/bold/italics formatting. Always use this function when done adjusting formatting, so make sure what you've set doesn't 'bleed' onto other triggers/aliases.
Parameters
None
Example
-- select and set the 'Tommy' to red in the line
if selectString("Tommy", 1) ~= -1 then fg("red") end
 
-- now reset the formatting, so our echo isn't red
resetFormat()
echo(" Hi Tommy!")
 
-- another example: just highlighting some words
for _, word in ipairs{"he", "she", "her", "their"} do
  if selectString(word, 1) ~= -1 then
    bg("blue")
  end
end
resetFormat()

selectCurrentLine

selectCurrentLine([windowName])
Selects the content of the current line that the cursor at. By default, the cursor is at the start of the current line that the triggers are processing, but you can move it with the moveCursor() function. Note Note: This selects the whole line, including the linebreak - so it has a subtle difference from the slightly slower selectString(line, 1) selection method.
See Also: selectString(), getCurrentLine()
Parameters
  • windowName:
Optional parameter to set the window in which to select text.
Example
-- color the whole line green!
selectCurrentLine()
fg("green")
deselect()
resetFormat()

setBackgroundColor

setBackgroundColor(labelName, red, green, blue, transparency)
Sets rgb color values and the transparency for the given window. Colors are from 0 to 255 (0 being black), and transparency is from - to 255 (0 being completely transparent).

Note Note: Transparency only works on labels, not miniConsoles for efficiency reasons.

Parameters
  • labelName:
The name of the label to change it's background color.
  • red:
Amount of red to use, from 255 (full) to 0 (none).
  • green:
Amount of green to use, from 255 (full) to 0 (none).
  • blue:
Amount of red to use, from 255 (full) to 0 (none).
  • transparency:
Amount of transparency to use, from 255 (fully opaque) to 0 (fully transparent).
Example
-- make a red label that's somewhat transparent
setBackgroundColor("some label",255,0,0,200)

setBackgroundImage

setBackgroundImage(labelName, imageLocation)
Loads an image file (png) as a background image for a label. This can be used to display clickable buttons in combination with setLabelClickCallback() and such.
Note you can only do this for labels, not miniconsoles.
Note you can also load images via setLabelStyleSheet().
Parameters
  • labelName:
The name of the label to change it's background color.
  • imageLocation:
The full path to the image location. It's best to use [[ ]] instead of "" for it - because for Windows paths, backslashes need to be escaped.
Example
-- give the top border a nice look
setBackgroundImage("top bar", [[/home/vadi/Games/Mudlet/games/top_bar.png]])

setBorderBottom

setBorderBottom(size)
Sets the size of the bottom border of the main window in pixels. A border means that the MUD text won't go on it, so this gives you room to place your graphical elements there.
See Also: setBorderColor()
Parameters
  • size:
Height of the border in pixels - with 0 indicating no border.
Example
setBorderLeft(100)

setBorderColor

setBorderColor(r,g,b)
Sets the color of the main windows border that you can create either with setBorderTop(), setBorderBottom(), setBorderLeft(), setBorderRight(), or via the main window settings.
See Also: setBorderTop(), setBorderBottom(), setBorderLeft(), setBorderRight()
Parameters
  • r:
Amount of red to use, from 0 to 255.
  • g:
Amount of green to use, from 0 to 255.
  • b:
Amount of blue to use, from 0 to 255.
Example
-- set the border to be completely blue
setBorderColor(0, 0, 255)
 
-- or red, using a name
setBorderColor( unpack(color_table.red) )

setBorderLeft

setBorderLeft(size)
Sets the size of the left border of the main window in pixels. A border means that the MUD text won't go on it, so this gives you room to place your graphical elements there.
See Also: setBorderColor()
Parameters
  • size:
Width of the border in pixels - with 0 indicating no border.
Example
setBorderLeft(100)

setBorderRight

setBorderRight(size)
Sets the size of the right border of the main window in pixels. A border means that the MUD text won't go on it, so this gives you room to place your graphical elements there.
See Also: setBorderColor()
Parameters
  • size:
Width of the border in pixels - with 0 indicating no border.
Example
setBorderRight(100)

setBorderTop

setBorderTop(size)
Sets the size of the top border of the main window in pixels. A border means that the MUD text won't go on it, so this gives you room to place your graphical elements there.
See Also: setBorderColor()
Parameters
  • size:
Height of the border in pixels - with 0 indicating no border.
Example
setBorderTop(100)

setLabelClickCallback

setLabelClickCallback(labelName, luaFunctionName, optional any amount of arguments)
Specifies a Lua function to be called if the user clicks on the label/image. This function can pass any number of string or integer number values as additional parameters. These parameters are then used in the callback - thus you can associate data with the label/button.
See Also: setLabelOnEnter(), setLabelOnLeave()
Parameters
  • labelName:
The name of the label to attach a callback function to.
  • luaFunctionName:
The Lua function name to call, as a string - it must be registered as a global function, and not inside any namespaces (tables).
  • optional any amount of arguments:
Optional arguments you'd like to pass to the calling function.
Example
function onClickGoNorth()
  echo("the north button was clicked!")
end
 
setLabelClickCallback( "compassNorthImage", "onClickGoNorth" )
 
-- you can also use them within tables now:
mynamespace = {
  onClickGoNorth = function()
    echo("the north button was clicked!")
  end
}
 
setLabelClickCallback( "compassNorthImage", "mynamespace.onClickGoNorth" )

setLabelOnEnter

setLabelClickCallback(labelName, luaFunctionName, optional any amount of arguments)
Specifies a Lua function to be called when the mouse enters within the labels borders. This function can pass any number of string or integer number values as additional parameters. These parameters are then used in the callback - thus you can associate data with the label/button.
See Also: setLabelClickCallback(), setLabelOnLeave()
Parameters
  • labelName:
The name of the label to attach a callback function to.
  • luaFunctionName:
The Lua function name to call, as a string - it must be registered as a global function, and not inside any namespaces (tables).
  • optional any amount of arguments:
Optional arguments you'd like to pass to the calling function.
Example
function onMouseOver()
  echo("The mouse is hovering over the label!\n")
end
 
setLabelOnEnter( "compassNorthImage", "onMouseOver" )

setLabelOnLeave

setLabelClickCallback(labelName, luaFunctionName, optional any amount of arguments)
Specifies a Lua function to be called when the mouse leaves the labels borders. This function can pass any number of string or integer number values as additional parameters. These parameters are then used in the callback - thus you can associate data with the label/button.
See Also: setLabelClickCallback(), setLabelOnEnter()
Parameters
  • labelName:
The name of the label to attach a callback function to.
  • luaFunctionName:
The Lua function name to call, as a string - it must be registered as a global function, and not inside any namespaces (tables).
  • optional any amount of arguments:
Optional arguments you'd like to pass to the calling function.
Example
function onMouseLeft(argument)
  echo("The mouse quit hovering over the label the label! We also got this as data on the function: "..argument)
end
 
setLabelOnLeave( "compassNorthImage", "onMouseLeft", "argument to pass to function" )

setLink

setLink([window, ]command, tooltip)
Turns the selected() text into a clickable link - upon being clicked, the link will do the command code. Tooltip is a string which will be displayed when the mouse is over the selected text.
Parameters
  • window:
optional: a miniconsole or a userwindow in which to select the text in.
  • command:
command to do when the text is clicked.
  • tooltip:
tooltip to show when the mouse is over the text - explaining what would clicking do.
Example
-- you can clickify a lot of things to save yourself some time - for example, you can change
--  the line where you receive a message to be clickable to read it!
-- prel regex trigger:
-- ^You just received message #(\w+) from \w+\.$
-- script:
selectString(matches[2], 1)
setUnderline(true) setLink([[send("msg read ]]..matches[2]..[[")]], "Read #"..matches[2])
resetFormat()
 
-- an example of selecting text in a miniconsole and turning it into a link:
 
HelloWorld = Geyser.MiniConsole:new({
  name="HelloWorld",
  x="70%", y="50%",
  width="30%", height="50%",
})
HelloWorld:echo("hi")
selectString("HelloWorld", "hi", 1)
setLink("HelloWorld", "echo'you clicked hi!'", "click me!")

setLabelStyleSheet

setLabelStyleSheet(label, markup)
Applies Qt style formatting to a label via a special markup language.
Parameters
  • label:
The name of the label to be formatted (passed when calling createLabel).
  • markup:
The string instructions, as specified by the Qt Style Sheet reference.
References
http://doc.qt.nokia.com/4.7/stylesheet-reference.html#list-of-properties
Example
-- This creates a label with a white background and a green border, with the text "test"
-- inside.
createLabel("test", 50, 50, 100, 100, 0)
setLabelStyleSheet("test", [[
	background-color: white;
	border: 10px solid green;
	font-size: 12px;
	]])
echo("test", "test")
 
-- This creates a label with a single image, that will tile or clip depending on the
-- size of the label. To use this example, please supply your own image.
createLabel("test5", 50, 353, 164, 55, 0)
setLabelStyleSheet("test5", [[
	background-image: url(C:/Users/Administrator/.config/mudlet/profiles/Midkemia Online/Vyzor/MkO_logo.png);
	]])
 
-- This creates a label with a single image, that can be resized (such as during a
-- sysWindowResizeEvent). To use this example, please supply your own image.
createLabel("test9", 215, 353, 100, 100, 0)
setLabelStyleSheet("test9", [[
	border-image: url(C:/Users/Administrator/.config/mudlet/profiles/Midkemia Online/Vyzor/MkO_logo.png);
	]])

setPopup

setPopup(name, {lua code}, {hints})
Turns the selected() text into a left-clickable link, and a right-click menu for more options. The selected text, upon being left-clicked, will do the first command in the list. Upon being right-clicked, it'll display a menu with all possible commands. The menu will be populated with hints, one for each line.
Parameters
  • name:
the name of the console to operate on. If not using this in a miniConsole, use "main" as the name.
  • {lua code}:
a table of lua code strings to do. ie,
{[[send("hello")]], [[echo("hi!"]]}
  • {hints}:
a table of strings which will be shown on the popup and right-click menu. ie,
{"send the hi command", "echo hi to yourself"}
.
Example
-- In a `Raising your hand in greeting, you say "Hello!"` exact match trigger, 
-- the following code will make left-clicking on `Hello` show you an echo, while right-clicking
-- will show some commands you can do.
 
selectString("Hello", 1)
setPopup("main", {[[send("bye")]], [[echo("hi!")]]}, {"left-click or right-click and do first item to send bye", "click to echo hi"})

showToolBar

showToolBar(name)
Makes a toolbar (a button group) appear on the screen.
Parameters
  • name:
name of the button group to display
Example
showToolBar("my offensive buttons")

wrapLine

wrapLine(windowName, lineNumber)
wraps the line specified by lineNumber of mini console (window) windowName. This function will interpret \n characters, apply word wrap and display the new lines on the screen. This function may be necessary if you use deleteLine() and thus erase the entire current line in the buffer, but you want to do some further echo() calls after calling deleteLine(). You will then need to re-wrap the last line of the buffer to actually see what you have echoed and get your \n interpreted as newline characters properly. Using this function is no good programming practice and should be avoided. There are better ways of handling situations where you would call deleteLine() and echo afterwards e.g.:
selectString(line,1)
replace("")

This will effectively have the same result as a call to deleteLine() but the buffer line will not be entirely removed. Consequently, further calls to echo() etc. sort of functions are possible without using wrapLine() unnecessarily.

See Also: replace(), deleteLine()
Parameters
  • windowName:
The miniconsole or the main window (use main for the main window)
  • lineNumber:
The line number which you'd like re-wrapped.
Example
-- re-wrap the last line in the main window
wrapLine("main", getLineCount())
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox