Manual:Lua Functions

From Mudlet
Jump to navigation Jump to search

Function Categories

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

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

  createMiniConsole()
  createLabel()
  createGauge()

</lua>

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.

String Functions : These functions are sued to manipulate strings.

Scripting Object Functions

Mapper Functions

Miscellaneous Functions

Database Functions

Variables

The following variables are provided by Mudlet:

line
This variable holds the content of the current line that is being processed by the trigger engine. The engine runs all triggers on each line as it arrives from the MUD.
command
This variable holds the current user command. This is typically used in alias scripts.
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. Have a look at this example.

Basic Essentials

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

debugc

debugc(content)
Again this will not send anything to anywhere. It will however print not to the main window, but only to the errors view. You need to open that window to see the message.
See also: Errors View

Note Note: Do not use this to display information to end-users. It will be hard to find. It is mainly useful for developing/debugging. Does not echo to the debug window

debugc(" Trigger successful!")
-- Text will be shown in errors view, not to main window.

display

display(content)
This is much like echo, in that is will show text at your screen, not send anything to anywhere. However, it also works with other objects than just text, like a number, table, function, or even many arguments at once. This function is useful to easily take a look at the values of a lua table, for example. If a value is a string of letters, it'll be in quotes, and if it's a number, it won't be quoted.

Note Note: Do not use this to display information to end-users. It may be hard to read. It is mainly useful for developing/debugging.

myTable = {} -- create an empty lua table
myTable.foo = "Hello there" -- add a text
myTable.bar = 23 -- add a number
myTable.ubar = function () echo("OK") end -- add more stuff
display( myTable ) -- take a look inside the table

echo

echo([miniconsoleName or labelName], text)
This function appends text at the end of the current line.
Parameters
  • miniconsoleName: (optional) the miniconsole to echo to, or:
  • labelName: (optional) the label to echo to.
  • text: text you'd like to see printed. You can use \n in an echo to insert a new line. If you're echoing this to a label, you can also use styling to color, center, increase/decrease size of text and various other formatting options as listed here.

See also: moveCursor(), insertText(), cecho(), decho(), hecho()

Technical Detail

As of Mudlet 4.8+, a single line is capped to 10,000 characters (this is when ~200 at most will fit on one line on your screen).


Example
-- a miniconsole example

-- first, determine the size of your screen
local windowWidth, windowHeight = getMainWindowSize()

-- create the miniconsole
createMiniConsole("sys", windowWidth-650,0,650,300)
setBackgroundColor("sys",255,69,0,255)
setMiniConsoleFontSize("sys", 8)
-- wrap lines in window "sys" at 40 characters per line - somewhere halfway, as an example
setWindowWrap("sys", 40)

echo("sys","Hello world!\n")
cecho("sys", "<:OrangeRed>This is random spam with the same background\n")
cecho("sys", "<blue:OrangeRed>and this is with a blue foreground. ")
cecho("sys", "<bisque:BlueViolet>Lastly, this is with both a foreground and a background.\n")
-- a label example

-- This example creates a transparent overlay message box to show a big warning message "You are under attack!" in the middle 
-- of the screen. Because the background color has a transparency level of 150 (0-255, with 0 being completely transparent 
-- and 255 opaque) the background text can still be read through.
local width, height = getMainWindowSize()
createLabel("messageBox",(width/2)-300,(height/2)-100,250,150,1)
resizeWindow("messageBox",500,70)
moveWindow("messageBox", (width/2)-300,(height/2)-100 )
setBackgroundColor("messageBox", 255, 204, 0, 200)
echo("messageBox", [[<p style="font-size:35px"><b><center><font color="red">You are under attack!</font></center></b></p>]])

printDebug

printDebug(msg, [showStackTrace])
Prints a debug message in green to the error console in the script editor only. Does not echo to the debug window or the main console. Includes stack trace if showStackTrace is included and not nil or false.
See also
printError, debugc
Mudlet VersionAvailable in Mudlet4.14+
Technical Note

Note Note: This will not be echoed to the main console even if the option to echo Lua errors to the main console is turned on. Does not echo to the debug window. As such you can use it for debugging information without fear it will be shown unless someone goes looking for errors.

Parameters
  • msg:
string to echo to the error console
  • showStackTrace:
(optional) boolean true if you want to include the stack trace, leave off if you do not.
Example
-- print a debug message to the error console for troubleshooting purposes, when you don't want to echo the information to the main screen.
-- the only difference between this and debugc is this includes information on the script/alias/trigger/etc and line it was called from, whereas debugc does not.
printDebug("Switching to chaos mode")

-- Want to record that something occurred, and include stacktrace so you can see what path the code was taking, but you don't want to halt execution or have it show up in main screen or in scary red.
printDebug("Something unexpected occurred but we can recover from it. Still, we want to be able to notice and troubleshoot it with extra information.", true)

printError

printError(msg, [showStackTrace], [haltExecution])
Prints an error message in red to the error console in the script editor. Can optionally include stacktrace information and halt execution.
See also
printDebug, debugc
Mudlet VersionAvailable in Mudlet4.14+
Technical Note

Note Note: This WILL be echoed to the main console if the option to echo Lua errors to the main console is turned on. You should not use this for idle debugging information, but actual errors that may put big red error lines in the main window.

Parameters
  • msg:
string to echo to the error console
  • showStackTrace:
(optional) true if you want to include the stack trace, leave off if you do not.
  • haltExecution:
(optional) true if you want to halt execution. You must pass a value for showStackTrace in order to halt execution.
Example
-- print an error message but do not include extra stack information or halt execution.
-- this is similar to debugc except it include more information on the place it was called from
-- and will show up in red and echo to the main console if the option for errors to echo there is selected.
printError("Your maxhp is below your currenthp and our game doesn't allow for that. HAX?!")

-- Something bad happened, for sure, but your script can recover.
-- Make sure this is something important enough it might make it to the main window as a big red error.
-- but we are not halting execution, since we can carry on in some capacity
printError("gmcp values for this thing went missing, will carry on using defaults but you should tell somebody about this.", true)

-- print an error message to the error console for troubleshooting purposes. 
-- Prints stack trace for troubleshooting and halts execution (because you cannot continue without the configuration, presumably)
-- similar to using error(msg) but includes the stacktrace information.
printError("Our entire configuration seems to have gone missing!", true, true)

send

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

See also: sendAll(), speedwalk()

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

Note Note: The game server can choose not to show commands sent on screen (for example, if you're typing in a password).

send("Hello Jane") --echos the command on the screen
send("Hello Jane", true) --echos the command on the screen
send("Hello Jane", false) --does not echo the command on the screen

-- use a variable in the send:
send("kick "..target)

-- to send directions:
speedwalk("s;s;w;w;w;w;w;w;w;")

-- to send many things:
sendAll("hi", "open door e", "e", "get item", "sit")


UI Functions

All functions that help you construct custom GUIs. They deal mainly with miniconsole/label/gauge creation and manipulation as well as displaying or formatting information on the screen.

addCommandLineMenuEvent

addCommandLineMenuEvent([window,] label, eventName)

Adds item to right click menu associated with command line.

Mudlet VersionAvailable in Mudlet4.14+
See also
removeCommandLineMenuEvent()
Parameters
  • window:
Window that command line belongs to. Optional, will default to "main" (main window console)
  • label:
Label of item
  • eventName:
Event name that will be fired when clicked.
Returns
  • Returns true if the mouse event was added successfully.
Example
addCommandLineMenuEvent("My very own special paste from clipboard", "pasteFromClipboardWithoutLineBreaks" )
registerAnonymousEventHandler("pasteFromClipboardWithoutLineBreaks", function()
  local text = string.gsub(getClipboardText(), "[\r|\n]", "")
  appendCmdLine(text)
end)

addMouseEvent

addMouseEvent(uniqueName, eventName, [displayName, tooltipText])
Registers a new context menu option when right-clicked on a console window. Will return true if the event was added successfully, otherwise nil+message will be returned. If the displayName isn't set, uniqueName will be used for the menu label. eventName should be a Mudlet event that will handle the click data that includes event, unique name, window name, selection upper left column and row and selection bottom right column and row in that order. This is intended to be used with available cursor functions for any selection or processing needs.
Mudlet VersionAvailable in Mudlet4.13+
See also
getMouseEvents(), moveCursor()
Parameters
  • uniqueName:
A unique identifier for the mouse event.
  • eventName:
Name of the Mudlet event that will handle the data.
  • displayName:
(optional) Label text for the mouse context menu. If not set, the label defaults to uniqueName.
  • tooltipText:
(optional) Tooltip text when mouse is hovered on the option. If not set, no tooltip will be visible.
Returns
  • Returns true if the mouse event was added successfully.
Example
-- An example showing implementing a hecho-friendly copy option:

addMouseEvent("hecho copy", "onMouseCopyExample")

function rgbToHex(r,g,b)
    local rgb = (r * 0x10000) + (g * 0x100) + b
    return string.format("#%x", rgb)
end

function onMouseCopyExample(event, menu, window, startCol, startRow, endCol, endRow)
  -- Check whether there's an actual selection
  if startCol == endCol and startRow == endRow then return end
  local parsed = ""
  local lastColor = nil
  -- Loop through each symbol within the range
  for l = startRow, endRow do
    local cStart = l == startRow and startCol or 0
    moveCursor(window, cStart, l)
    local cEnd = l == endRow and endCol or #getCurrentLine() - 1
    for c = cStart, cEnd do
      selectSection(window, c, 1)
      local symbol = getSelection(window) or ""
      -- Convert the foreground color to a hex format, suitable for hecho
      local color = rgbToHex(getFgColor(window))
      -- Don't repeat the color if previous one was the same
      if color == lastColor then
        parsed = parsed .. symbol
      else
        lastColor = color
        parsed = parsed .. color .. symbol
      end
    end
    if l ~= endRow then parsed = parsed .. "\n" end
  end
  setClipboardText(parsed)
end

registerAnonymousEventHandler("onMouseCopyExample", "onMouseCopyExample")

ansi2decho

ansi2decho(text, default_colour)
Converts ANSI colour sequences in text to colour tags that can be processed by the decho() function.
See also: decho()
Mudlet VersionAvailable in Mudlet3.0+

Note Note: ANSI bold is available since Mudlet 3.7.1+.

Note Note: underline, italics, overline, and strikethrough supported since Mudlet 4.15+

Parameters
  • text:
String that contains ANSI colour sequences that should be replaced.
  • default_colour:
Optional - ANSI default colour code (used when handling orphan bold tags).
Return values
  • string text:
The decho-valid converted text.
  • string colour:
The ANSI code for the last used colour in the substitution (useful if you want to colour subsequent lines according to this colour).
Example
local replaced = ansi2decho('\27[0;1;36;40mYou say in a baritone voice, "Test."\27[0;37;40m')
-- 'replaced' should now contain <r><0,255,255:0,0,0>You say in a baritone voice, "Test."<r><192,192,192:0,0,0>
decho(replaced)

Or show a complete colourful squirrel! It's a lotta code to do all the colours, so click the Expand button on the right to show it:

decho(ansi2decho([[
                                                  �[38;5;95m▄�[48;5;95;38;5;130m▄▄▄�[38;5;95m█�[49m▀�[0m    �[0m
╭───────────────────────╮          �[38;5;95m▄▄�[0m          �[38;5;95m▄�[48;5;95;38;5;130m▄▄�[48;5;130m█�[38;5;137m▄�[48;5;137;38;5;95m▄�[49m▀�[0m      �[0m
│                       │         �[48;5;95;38;5;95m█�[48;5;137;38;5;137m██�[48;5;95m▄�[49;38;5;95m▄▄▄�[48;5;95;38;5;137m▄▄▄�[49;38;5;95m▄▄�[48;5;95;38;5;130m▄�[48;5;130m███�[38;5;137m▄�[48;5;137m█�[48;5;95;38;5;95m█�[0m       �[0m
│  Encrypt everything!  │       �[38;5;95m▄�[48;5;187;38;5;16m▄�[48;5;16;38;5;187m▄�[38;5;16m█�[48;5;137;38;5;137m███�[38;5;187m▄�[38;5;16m▄▄�[38;5;137m██�[48;5;95;38;5;95m█�[48;5;130;38;5;130m█████�[48;5;137;38;5;137m██�[48;5;95;38;5;95m█�[0m       �[0m
│                       ├────  �[38;5;95m▄�[48;5;95;38;5;137m▄�[48;5;16m▄▄▄�[48;5;137m███�[48;5;16;38;5;16m█�[48;5;187m▄�[48;5;16m█�[48;5;137;38;5;137m█�[48;5;95;38;5;95m█�[48;5;130;38;5;130m██████�[48;5;137;38;5;137m███�[48;5;95;38;5;95m█�[0m      �[0m
╰───────────────────────╯      �[48;5;95;38;5;95m█�[48;5;137;38;5;137m██�[48;5;16m▄�[38;5;16m█�[38;5;137m▄�[48;5;137m██████�[48;5;95;38;5;95m█�[48;5;130;38;5;130m██████�[48;5;137;38;5;137m████�[48;5;95m▄�[49;38;5;95m▄�[0m    �[0m
                                �[38;5;95m▀�[48;5;137m▄�[38;5;137m███████�[38;5;95m▄�[49m▀�[0m �[48;5;95;38;5;95m█�[48;5;130;38;5;130m██████�[48;5;137;38;5;137m████�[48;5;95m▄�[49;38;5;95m▄�[0m   �[0m
                                  �[48;5;95;38;5;187m▄▄▄�[38;5;137m▄�[48;5;137m██�[48;5;95;38;5;95m█�[0m    �[48;5;95;38;5;95m█�[48;5;130;38;5;130m███████�[48;5;137;38;5;137m███�[48;5;95m▄�[49;38;5;95m▄�[0m  �[0m
                                 �[38;5;187m▄�[48;5;187m███�[48;5;137;38;5;137m████�[48;5;95;38;5;95m█�[0m   �[48;5;95;38;5;95m█�[48;5;130;38;5;130m█████████�[48;5;137;38;5;137m███�[48;5;95;38;5;95m█�[0m �[0m
                                �[38;5;187m▄�[48;5;187m███�[38;5;137m▄�[48;5;137m█�[48;5;95;38;5;95m█�[48;5;137;38;5;137m███�[48;5;95m▄�[49;38;5;95m▄�[0m  �[38;5;95m▀�[48;5;130m▄�[38;5;130m███████�[48;5;137;38;5;137m████�[48;5;95;38;5;95m█�[0m�[0m
                               �[48;5;95;38;5;95m█�[48;5;187;38;5;187m████�[48;5;137;38;5;137m██�[48;5;95m▄�[48;5;137;38;5;95m▄�[38;5;137m██�[38;5;95m▄�[38;5;137m█�[48;5;95m▄�[49;38;5;95m▄�[0m �[48;5;95;38;5;95m█�[48;5;130;38;5;130m███████�[48;5;137;38;5;137m████�[48;5;95;38;5;95m█�[0m�[0m
                              �[38;5;95m▄�[48;5;95;38;5;137m▄�[48;5;187;38;5;187m████�[48;5;137;38;5;137m███�[48;5;95;38;5;95m█�[48;5;137;38;5;137m██�[48;5;95;38;5;95m█�[48;5;137;38;5;137m██�[48;5;95m▄�[49;38;5;95m▄�[0m �[48;5;95;38;5;95m█�[48;5;130;38;5;130m██████�[48;5;137;38;5;137m████�[48;5;95;38;5;95m█�[0m�[0m
                           �[38;5;95m▄�[48;5;95m██�[48;5;137m▄▄�[48;5;187;38;5;187m████�[48;5;137;38;5;95m▄▄�[48;5;95;38;5;137m▄�[48;5;137m█�[38;5;95m▄�[48;5;95;38;5;137m▄�[48;5;137m████�[48;5;95;38;5;95m█�[0m �[48;5;95;38;5;95m█�[48;5;130;38;5;130m██████�[48;5;137;38;5;137m████�[48;5;95;38;5;95m█�[0m�[0m
                                �[48;5;187;38;5;187m███�[48;5;95m▄�[38;5;137m▄▄▄▄�[48;5;137m██████�[48;5;95;38;5;95m█�[49m▄�[48;5;95;38;5;130m▄�[48;5;130m██████�[48;5;137;38;5;137m███�[38;5;95m▄�[49m▀�[0m�[0m
                                �[48;5;187;38;5;95m▄�[38;5;187m████�[48;5;137;38;5;137m█�[38;5;95m▄�[48;5;95;38;5;137m▄�[48;5;137m█████�[48;5;95;38;5;95m█�[48;5;130;38;5;130m███████�[38;5;137m▄�[48;5;137m████�[48;5;95;38;5;95m█�[0m �[0m
                                �[48;5;95;38;5;95m█�[48;5;187;38;5;137m▄�[38;5;187m███�[48;5;95;38;5;95m█�[48;5;137;38;5;137m██████�[48;5;95m▄▄�[48;5;130m▄▄▄▄▄�[48;5;137m██████�[48;5;95;38;5;95m█�[0m  �[0m
                              �[38;5;95m▄▄▄�[48;5;95;38;5;137m▄�[48;5;187m▄�[38;5;187m██�[48;5;95m▄�[48;5;137;38;5;95m▄�[38;5;137m█████�[38;5;95m▄�[38;5;137m███████████�[48;5;95;38;5;95m█�[0m   �[0m
                            �[38;5;95m▀▀▀▀▀▀▀▀�[48;5;187m▄▄▄�[48;5;95;38;5;137m▄�[48;5;137m██�[38;5;95m▄�[49m▀�[0m �[38;5;95m▀▀�[48;5;137m▄▄▄▄▄▄�[49m▀▀▀�[0m    �[0m
                                  �[38;5;95m▀▀▀▀▀▀▀▀▀�[0m                 �[0m
                                                                    ]]))

Squirrel-in-Mudlet.png

ansi2string

ansi2string(text)
Strips ANSI colour sequences from a string (text)
See also: ansi2decho()
Mudlet VersionAvailable in Mudlet4.10+
Parameters
  • text:
String that contains ANSI colour sequences that should be removed.
Return values
  • string text:
The plain text without ANSI colour sequences.
Example
local replaced = ansi2string('\27[0;1;36;40mYou say in a baritone voice, "Test."\27[0;37;40m')
-- 'replaced' should now contain You say in a baritone voice, "Test."
print(replaced)

appendBuffer

appendBuffer(name)
Pastes the previously copied rich text (including text formats like color etc.) into user window name.
See also: selectCurrentLine(), copy(), 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 (since Mudlet 3.0).
  • 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(window_or_fontsize, [fontname])
Returns the average height and width of characters in a particular window, or a font name and size combination. Helpful if you want to size a miniconsole to specific dimensions.
Returns two numbers, width/height
See also: setMiniConsoleFontSize(), getMainWindowSize()
Parameters
  • window_or_fontsize:
The miniconsole or font size you are wanting to calculate pixel sizes for.
  • fontname:
Specific font name (along with the size as the first argument) to calculate for.

Note Note: Window as an argument is available in Mudlet 3.10+, and font name in Mudlet 4.1+.

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 and the below tags. You can also include unicode art in it - try some examples from 1lineart.
Formatting
<b>  - bold
</b> - bold off
<i>  - italics
</i> - italics off
<u>  - underline
</u> - underline off
<o>  - overline
</o> - overline off
<s>  - strikethrough
</s> - strikethrough off
See also: decho(), hecho(), creplaceLine()

Note Note: Support for labels added in Mudlet 4.15; however, it does not turn a label into a miniconsole and every time you cecho it will erase any previous echo sent to the label.

Parameters
  • window:
Optional - the window name to echo to - can either be none or "main" for the main window, or a miniconsole, userwindow, or label 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 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("\n<red>Red text with <i>italics</i>, <u>underline</u>, <s>strikethrough</s>, <o>overline</o>, and <b>bold</b>.")

cecho("\n<green><o><u>Green text with over and underline at the same time.</o></u>")

-- \n adds a new line
cecho("<red>one line\n<green>another line\n<blue>last line")

cecho("myinfo", "<green>All of this text is green in the myinfo miniconsole.")

cecho("<green>(╯°□°)<dark_green>╯︵ ┻━┻")

cecho("°º¤ø,¸¸,ø¤º°`°º¤ø,¸,ø¤°º¤ø,¸¸,ø¤º°`°º¤ø,¸")

cecho([[
 ██╗    ██╗     ██╗███╗   ██╗███████╗     █████╗ ██████╗ ████████╗
███║    ██║     ██║████╗  ██║██╔════╝    ██╔══██╗██╔══██╗╚══██╔══╝
╚██║    ██║     ██║██╔██╗ ██║█████╗      ███████║██████╔╝   ██║
 ██║    ██║     ██║██║╚██╗██║██╔══╝      ██╔══██║██╔══██╗   ██║
 ██║    ███████╗██║██║ ╚████║███████╗    ██║  ██║██║  ██║   ██║
 ╚═╝    ╚══════╝╚═╝╚═╝  ╚═══╝╚══════╝    ╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝
]])

cechoLink

cechoLink([windowName], text, command, hint, true)
Echos a piece of text as a clickable link, at the end of the current selected line - similar to cecho(). This version allows you to use colours within your link text.
See also: echoLink(), dechoLink(), hechoLink()
Parameters
  • windowName:
optional parameter, allows selection between sending the link to a miniconsole or the main window.
  • text:
text to display in the echo. Same as a normal cecho().
  • command:
Lua code to do when the link is clicked, as text or a function (since Mudlet 4.11).
  • hint:
text for the tooltip to be displayed when the mouse is over the link.
  • true:
requires argument for the colouring to work.
Example
-- echo a link named 'press me!' that'll send the 'hi' command to the game
cechoLink("<red>press <brown:white>me!", function() send("hi") end, "This is a tooltip", true)

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
cechoLink("<red>press <brown:white>me!", [[send("hi")]], "This is a tooltip", true)

cecho2ansi

ansiFormattedString = cecho2ansi(text)
Converts cecho formatted text to ansi formatted text. Used by cfeedTriggers, but useful if you want ansi formatted text for any other reason.
See also
cecho(), cfeedTriggers()
Mudlet VersionAvailable in Mudlet4.15+

Note Note: This function uses the ansi short colors (0-15) for color names which have base 16 ansi equivalents, such as 'red', 'blue', "lightBlue", "cyan", etc rather than the values defined in the color_table. If there is no base ansi equivalent then it will use the rgb values from the color_table for the color.

Parameters
  • text:
The cecho formatted text for conversion
Returns
  • String converted to ansi formatting
Example
-- replicates the functionality of cfeedTriggers() for a single line.
-- you would most likely just use cfeedTriggers, but it makes for a tidy example.
feedTriggers(cecho2ansi("\n<red>This is red.<reset> <i>italic</i>, <b>bold</b>, <s>strikethrough</s>, <u>underline</u>\n"))


cechoPopup

cechoPopup([windowName], text, {commands}, {hints}, [useCurrentFormatElseDefault])
Creates text with a left-clickable link, and a right-click menu for more options at the end of the current line, like cecho(). 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.
Mudlet VersionAvailable in Mudlet4.1+
Parameters
  • windowName:
(optional) name of the window to echo to. Use either main or omit for the main window, or the miniconsoles name otherwise.
  • text:
the text to display
  • {commands}:
a table of lua code to do, in text strings or as functions (since Mudlet 4.11), i.e. {[[send("hello")]], function() echo("hi!") end}
  • {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"}
  • useCurrentFormatElseDefault:
(optional) 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:
cechoPopup("<red>activities<reset> to do", {function() send "sleep" end, function() send "sit" end, function() send "stand" end}, {"sleep", "sit", "stand"}, true)

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
cechoPopup("<red>activities<reset> to do", {[[send "sleep"]], [[send "sit"]], [[send "stand"]]}, {"sleep", "sit", "stand"}, true)

cinsertLink

cinsertLink([windowName], text, command, hint, true)
Echos a piece of text as a clickable link, at the end of the current cursor position - similar to cinsertText(). This version allows you to use colours within your link text.
See also: insertLink(), hinsertLink()
Mudlet VersionAvailable in Mudlet4.1+
Parameters
  • windowName:
optional parameter, allows selection between sending the link to a miniconsole or the main window.
  • text:
text to display in the echo. Same as a normal cecho().
  • command:
Lua code to do when the link is clicked, as text or a function (since Mudlet 4.11).
  • hint:
text for the tooltip to be displayed when the mouse is over the link.
  • true:
requires argument for the colouring to work.
Example
-- echo a link named 'press me!' that'll send the 'hi' command to the game
cinsertLink("<red>press <brown:white>me!", function() send("hi") end, "This is a tooltip", true)

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
cinsertLink("<red>press <brown:white>me!", [[send("hi")]], "This is a tooltip", true)

cinsertPopup

cinsertPopup([windowName], text, {commands}, {hints}, [useCurrentFormatElseDefault])
Creates text with a left-clickable link, and a right-click menu for more options at the end of the current cursor position, like cinsertText(). 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.
Mudlet VersionAvailable in Mudlet4.1+
Parameters
  • windowName:
(optional) name of the window to echo to. Use either main or omit for the main window, or the miniconsoles name otherwise.
  • text:
the text to display
  • {commands}:
a table of lua code to do, in text strings or as functions (since Mudlet 4.11), i.e. {[[send("hello")]], function() echo("hi!") end}
  • {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"}
  • useCurrentFormatElseDefault:
(optional) 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:
cinsertPopup("<red>activities<reset> to do", {function() send "sleep" end, function() send "sit" end, function() send "stand" end}, {"sleep", "sit", "stand"}, true)

-- Create some text as a clickable with a popup menu:
cinsertPopup("<red>activities<reset> to do", {[[send "sleep"]], [[send "sit"]], [[send "stand"]]}, {"sleep", "sit", "stand"}, true)

cinsertText

cinsertText([window], text)
inserts text at the current cursor position, with the possibility for color tags.
See Also: cecho(), creplaceLine()
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])
This is (now) identical to clearWindow().

clearWindow

clearWindow([windowName])
Clears the label, mini console, or user window 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.
Parameters
  • windowName:
(optional) The name of the label, mini console, or 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
clearWindow()

closestColor

closestColor(colorOrR[,G,B])
Returns the closest color from the color_table to the one provided for use in cecho and associated functions.
Mudlet VersionAvailable in Mudlet4.13+
Parameters
  • colorOrR:
Either the string representation of a color from decho or hecho (IE "#ff0077" or "<255,0,128>"), a table of color values (IE {255,0,18}), or the Red component of RGB when followed by two next optional parameters
  • G:
(optional) green component of RGB coordinates. Only needed if first parameter sent as the Red component only
  • B:
(optional) blue component of RGB coordinates. Only needed if first parameter sent as the Red component only
Returns
  • The closest color name from the color_table to the one supplied on success
  • nil + error if it cannot parse the parameters into a color.
Example
local colorName = closestColor(255, 0, 0) -- "ansi_light_red"
local colorName = closestColor({127, 255, 127}) -- "ansi_120"
local colorName = closestColor("<127, 127, 127>") -- "ansi_008"
local colorName = closestColor("#a020e6") -- "purple"
local colorName = closestColor("blue") -- "blue" (you wouldn't necessarily do this on purpose, but during automated color conversions this might occur)

copy

copy([windowName])
Copies the current selection to the lua virtual clipboard. This function operates on rich text, i. e. the selected text including all its format codes like colors, fonts etc. in the lua virtual clipboard until it gets overwritten by another copy operation.
See also: selectString(), selectCurrentLine(), paste(), appendBuffer(), replace(), createMiniConsole(), openUserWindow()
Parameters
  • windowName (optional):
the window from which to copy text - use the main console if not specified.
Example
-- This script copies the current line on the main screen to a window (miniconsole or userwindow) called 'chat' and gags the output on the main screen.
selectString(line, 1)
copy()
appendBuffer("chat")
replace("This line has been moved to the chat window!")

copy2decho

copy2decho([window], [stringToCopy], [instanceToCopy])
Copies a string from the current line of window, including color information in decho format.
See also: decho()
Mudlet VersionAvailable in Mudlet4.8+
Parameters
  • window (optional):
the window to copy the text from. Defaults to "main".
  • stringToCopy (optional):
the string to copy. Defaults to copying the entire line.
  • instanceToCopy (optional):
the instance of the string to copy. Defaults to 1.
Example
-- This copies the current line on the main console and dechos it to a miniconsole named "test"
decho("test", copy2decho())
-- This when put into a trigger would copy matches[2] with color information and decho it to a Geyser miniconsole stored as the variable enemylist
enemylist:decho(copy2decho(matches[2]))

copy2html

copy2html([window], [stringToCopy], [instanceToCopy])
Copies a string from the current line of window, including color information in html format for echoing to a label.
Mudlet VersionAvailable in Mudlet4.8+
Parameters
  • window (optional):
the window to copy the text from. Defaults to "main"
  • stringToCopy (optional):
the string to copy. Defaults to copying the entire line
  • instanceToCopy (optional):
the instance of the string to copy. Defaults to 1
Example
-- This copies the current line on the main console and echos it to a label named "TestLabel"
echo("TestLabel", copy2html())
-- This when put into a trigger would copy matches[2] with color information and echo it to a Geyser label stored as the variable enemylist
enemylist:echo(copy2html(matches[2]))

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.
See also: selectString(), selectCurrentLine(), copy(), paste()
Parameters
  • name:
The name of the buffer to create.
Example
--This creates a named buffer called "scratchpad"
createBuffer("scratchpad")

createCommandLine

createCommandLine([name of userwindow], name, x, y, width, height)
Creates a new command line inside the main window of Mudlet. If only a command line inside a miniConsole/UserWindow is needed see enableCommandLine().
You can use appendCmdLine() / getCmdLine() and other command line functions to customize the input.

Note Note: setCmdLineAction allows you to attach an action to your command line input.

Returns true or false.
See also: enableCommandLine(), disableCommandLine(), clearCmdLine(), getCmdLine(), printCmdLine(), appendCmdLine(), , selectCmdLineText()
Parameters
  • name of userwindow:
Name of userwindow the command line is created in. Optional, defaults to the main window if not provided.
  • name:
The name of the command line. Must be unique. Passed as a string.
  • x, y, width, height
Parameters to set the command line size and location - it is also possible to set them by using moveWindow() and resizeWindow(), as createCommandLine() will only set them once.
Mudlet VersionAvailable in Mudlet4.10+

createConsole

createConsole([name of userwindow], consoleName, fontSize, charsPerLine, numberOfLines, Xpos, Ypos)
Makes a new miniconsole which can be sized based upon the width of a 'W' character and the extreme top and bottom positions any character of the font should use. The background will be black, and the text color white.
Parameters
  • name of userwindow:
Name of userwindow your new miniconsole is created in. Optional, defaults to the main window if not provided.
  • 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.

Note Note: userwindow argument only available in 4.6.1+

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)

Note Note:

(For Mudlet Makers) This function is implemented outside the application's core via the GUIUtils.lua file of the Mudlet supporting Lua code using createMiniConsole() and other functions to position and size the mini-console and configure the font.

createGauge

createGauge([name of userwindow], name, width, height, Xpos, Ypos, gaugeText, r, g, b, orientation)
createGauge([name of userwindow], name, width, height, Xpos, Ypos, gaugeText, colorName, orientation)
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(), setGaugeStyleSheet()
Parameters
  • name of userwindow:
Name of userwindow the gauge is created in. Optional, defaults to the main window if not provided.
  • 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.
  • orientation:
the gauge orientation. Can be horizontal (fills from left to right), vertical (fills bottom to top), goofy (fills right to left), or batty (fills top to bottom).

Note Note: userwindow argument only available in 4.6.1+

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 of userwindow], name, Xpos, Ypos, width, height, fillBackground, [enableClickthrough])
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(), getTextFormat(), moveWindow(), setBackgroundColor(), getMainWindowSize(), calcFontSize(), deleteLabel()
Parameters
  • name of userwindow: Name of userwindow label is created in. Optional, defaults to the main window if not provided.
  • name: 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: width of the label, in pixels. Passed as an integer number.
  • height: height of the label, in pixels. Passed as an integer number.
  • fillBackground: whether or not to display the background. Passed as integer number (1 or 0) or as boolean (true, false). 1 or true will display the background color, 0 or false will not.
  • enableClickthrough: whether or not enable clickthrough on this label. Passed as integer number (1 or 0) or as boolean (true, false). 1 or true will enable clickthrough, 0 or false will not. Optional, defaults to clickthrough not enabled if not provided.

Note Note: userwindow argument only available in 4.6.1+

Example
-- a label situated at x=300 y=400 with dimensions 100x200
createLabel("a very basic label",300,400,100,200,1)
-- this example creates a transparent overlay message box to show a big warning message "You are under attack!" in the middle
-- of the screen. Because the background color has a transparency level of 150 (0-255, with 0 being completely transparent
-- and 255 opaque) the background text can still be read through.
local width, height = getMainWindowSize()
createLabel("messageBox",(width/2)-300,(height/2)-100,250,150,1)
resizeWindow("messageBox",500,70)
moveWindow("messageBox", (width/2)-300,(height/2)-100 )
setBackgroundColor("messageBox", 255, 204, 0, 200)
echo("messageBox", [[<p style="font-size:35px"><b><center><font color="red">You are under attack!</font></center></b></p>]])

-- you can also make it react to clicks!
mynamespace = {
  messageBoxClicked = function()
    echo("hey you've clicked the box!\n")
  end
}

setLabelClickCallback("messageBox", "mynamespace.messageBoxClicked")


-- uncomment code below to make it also hide after a short while
-- tempTimer(2.3, [[hideWindow("messageBox")]] ) -- close the warning message box after 2.3 seconds

createMiniConsole

createMiniConsole([name of userwindow], name, x, y, width, height)
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 setBorderSizes(), setBorderColor() functions.
Returns true or false.
See also: createLabel(), hideWindow(), showWindow(), resizeWindow(), setTextFormat(), getTextFormat(), moveWindow(), setMiniConsoleFontSize(), handleWindowResizeEvent(), setBorderSizes(), setWindowWrap(), getMainWindowSize(), setMainWindowSize(), calcFontSize()
Parameters
  • name of userwindow: (available in Mudlet 4.6.1+)
(Optional) name of userwindow the miniconsole is created in. Defaults to the main window if not provided.
  • name:
The name of the miniconsole. Must be unique. Passed as a string.
  • x, y, width, height
Parameters to set set the window size and location - in Mudlet version 2.1 and below it's best to set them via moveWindow() and resizeWindow(), as createMiniConsole() will only set them once. Starting with Mudlet version 3.0, however, that is fine and calling createMiniConsole() will re-position your miniconsole appropriately.

createScrollBox

createScrollBox([name of parent window], name, x, y, width, height)
creates a graphical elements able to hold other graphical elements such as labels, miniconsoles, command lines etc. in it.

If the added elements don't fit into the ScrollBox scrollbars appear and allow scrolling.

Returns true or false.
See also: createLabel(), hideWindow(), showWindow(), resizeWindow(), moveWindow(), setWindow()
Mudlet VersionAvailable in Mudlet4.15+
Parameters
  • name of parent window:
(Optional) name of the parent window the scrollBox is created in. Defaults to the main window if not provided.
  • name:
The name of the scrollBox. Must be unique. Passed as a string.
  • x, y, width, height
Parameters to set set the window size and location
Example
-- create a ScrollBox with the name sBox
createScrollBox("SBox",0,0,300,200)

-- create 3 Labels and put them into the ScrollBox
createLabel("SBox","SBoxLabel",0,0,200,200,1)
createLabel("SBox","SBoxLabel2",200,0,200,200,1)
createLabel("SBox","SBoxLabel3",400,0,200,200,1)

-- put some text on the labels
echo("SBoxLabel","Label")
echo("SBoxLabel2","Label2")
echo("SBoxLabel3","Label3")

-- change the colours of the labels to make it easier to distinguish them
setBackgroundColor("SBoxLabel",255,0,0)
setBackgroundColor("SBoxLabel2",0,255,0)
setBackgroundColor("SBoxLabel3",0,0,255)

creplace

creplace([window, ]text)
Replaces the output line from the game with a colour-tagged string.

See Also: cecho(), cinsertText()

Parameters
  • window:
    The window to replace the selection in. Optional, defaults to the main window if not provided.
  • text:
    The text to display, with color names inside angle brackets as with cecho(). You can select any from this list: Color Table
Example
selectCaptureGroup(1)
creplace("<magenta>[ALERT!]: <reset>"..matches[2])

creplaceLine

creplaceLine ([window], text)
Replaces the output line from the game with a colour-tagged string.

See Also: cecho(), cinsertText()

Parameters
  • window (optional):
the window to copy the text from. Defaults to "main". Only supported in Mudlet 4.12+
  • 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 colon : - <:red>. You can use the <reset> tag to reset to the default color. You can select any from this list: Color Table
Example
creplaceLine("<magenta>[ALERT!]: <reset>"..line)

decho

decho ([name of console,] text)
Color changes can be made using the format <FR,FG,FB:BR,BG,BB,[BA]> 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,[BA]>. 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").
You can also include the below tags.
Formatting
<b>  - bold
</b> - bold off
<i>  - italics
</i> - italics off
<u>  - underline
</u> - underline off
<o>  - overline
</o> - overline off
<s>  - strikethrough
</s> - strikethrough off
<r> - reset formatting

Note Note: Support for labels added in Mudlet 4.15; however, it does not turn a label into a miniconsole and every time you decho it will erase any previous echo sent to the label.

See also: cecho(), hecho(), copy2decho()
Parameters
  • name of console
(Optional) Name of the console to echo to. If no name is given, this will defaults to the main window.
  • text:
The text that you’d like to echo with embedded color tags. Tags take the RGB values only, see below for an explanation.


Note Note: Optional background transparancy parameter (BA) available in Mudlet 4.10+

Example
decho("<50,50,0:0,255,0>test")

decho("miniconsolename", "<50,50,0:0,255,0>test")

decho("\n<255,0,0>Red text with <i>italics</i>, <u>underline</u>, <s>strikethrough</s>, and <b>bold</b> formatting.")

decho("<\n<0,128,0><o><u>Green text with both over and underlines.</u></o>")

decho2ansi

ansiFormattedString = decho2ansi(text)
Converts decho formatted text to ansi formatted text. Used by dfeedTriggers, but useful if you want ansi formatted text for any other reason.
See also
decho(), dfeedTriggers()
Mudlet VersionAvailable in Mudlet4.10++

Note Note: non-color formatting added in Mudlet 4.15+

Parameters
  • text:
The decho formatted text for conversion
Returns
  • String converted to ansi formatting
Example
-- replicates the functionality of dfeedTriggers() for a single line.
-- you would most likely just use dfeedTriggers, but it makes for a tidy example.
feedTriggers(decho2ansi("\n<128,0,0>This is red.<r> <i>italic</i>, <b>bold</b>, <s>strikethrough</s>, <u>underline</u>\n"))

dechoLink

dechoLink([windowName], text, command, hint, true)
Echos a piece of text as a clickable link, at the end of the current selected line - similar to decho(). This version allows you to use colours within your link text.
Parameters
  • windowName:
(optional) allows selection between sending the link to a miniconsole or the "main" window.
  • text:
text to display in the echo. Same as a normal decho().
  • command:
Lua code to do when the link is clicked, as text or a function (since Mudlet 4.11).
  • hint:
text for the tooltip to be displayed when the mouse is over the link.
  • true:
requires argument for the colouring to work.
Example
-- echo a link named 'press me!' that'll send the 'hi' command to the game
dechoLink("<50,50,0:0,255,0>press me!", function() send("hi") end, "This is a tooltip", true)

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
dechoLink("<50,50,0:0,255,0>press me!", [[send("hi")]], "This is a tooltip", true)

dechoPopup

dechoPopup([windowName], text, {commands}, {hints}, [useCurrentFormatElseDefault])
Creates text with a left-clickable link, and a right-click menu for more options at the end of the current line, like decho(). 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.
Mudlet VersionAvailable in Mudlet4.1+
Parameters
  • windowName:
(optional) name of the window to echo to. Use either main or omit for the main window, or the miniconsoles name otherwise.
  • text:
the text to display
  • {commands}:
a table of lua code strings to do or a functions (since Mudlet 4.11). ie, {[[send("hello")]], function() echo("hi!") end}
  • {hints}:
a table of lua code to do, in text strings or as functions (since Mudlet 4.11), i.e. {"send the hi command", "echo hi to yourself"}
  • useCurrentFormatElseDefault:
(optional) 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:
dechoPopup("<255,0,0>activities<r> to do", {function() send "sleep" end, function() send "sit" end, function() send "stand" end}, {"sleep", "sit", "stand"}, true)

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
dechoPopup("<255,0,0>activities<r> to do", {[[send "sleep"]], [[send "sit"]], [[send "stand"]]}, {"sleep", "sit", "stand"}, true)

dinsertLink

dinsertLink([windowName], text, command, hint, true)
Echos a piece of text as a clickable link, at the end of the current cursor position - similar to dinsertText(). This version allows you to use colours within your link text.
See also: insertLink(), hinsertLink()
Mudlet VersionAvailable in Mudlet4.1+
Parameters
  • windowName:
optional parameter, allows selection between sending the link to a miniconsole or the main window.
  • text:
text to display in the echo. Same as a normal decho().
  • command:
Lua code to do when the link is clicked, as text or a function (since Mudlet 4.11).
  • hint:
text for the tooltip to be displayed when the mouse is over the link.
  • true:
requires argument for the colouring to work.
Example
-- echo a link named 'press me!' that'll send the 'hi' command to the game
dinsertLink("<255,0,0>press <165,42,42:255,255,255>me!", function() send("hi") end, "This is a tooltip", true)

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
dinsertLink("<255,0,0>press <165,42,42:255,255,255>me!", [[send("hi")]], "This is a tooltip", true)

dinsertPopup

dinsertPopup([windowName], text, {commands}, {hints}, [useCurrentFormatElseDefault])
Creates text with a left-clickable link, and a right-click menu for more options at the end of the current cursor position, like dinsertText(). 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.
Mudlet VersionAvailable in Mudlet4.1+
Parameters
  • windowName:
(optional) name of the window to echo to. Use either main or omit for the main window, or the miniconsoles name otherwise.
  • text:
the text to display
  • {commands}:
a table of lua code to do, in text strings or as functions (since Mudlet 4.11), i.e. {[[send("hello")]], function() echo("hi!") end}
  • {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"}
  • useCurrentFormatElseDefault:
(optional) 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:
dinsertPopup("<255,0,0>activities<r> to do", {function() send "sleep" end, function() send "sit" end, function() send "stand" end}, {"sleep", "sit", "stand"}, true)

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
dinsertPopup("<255,0,0>activities<r> to do", {[[send "sleep"]], [[send "sit"]], [[send "stand"]]}, {"sleep", "sit", "stand"}, true)

deleteLabel

deleteLabel(labelName)
Deletes and removes a label from the screen. Note that if you'd like to show the label again, it is much more performant to hide/show it instead.
Note that you shouldn't use the Geyser label associated with the label you delete afterwards - that doesn't make sense and Geyser right now wouldn't know that it's been deleted, either.
See also: hideWindow(), showWindow(), createLabel()
Parameters
  • labelName: name of the label to delete.
createLabel("a very basic label",300,400,100,200,1)
setBackgroundColor("a very basic label", 255, 204, 0, 200)

-- delete the label after 3 seconds
tempTimer(3, function()
  deleteLabel("a very basic label")
end)
Mudlet VersionAvailable in Mudlet4.5+

deleteLine

deleteLine([windowName])
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. This is purely visual - triggers will still fire on the line as expected.
See also: replace(), wrapLine()
Parameters
  • windowName:
(optional) name of the window to delete the line in. If no name is given, 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([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.
See also: selectString(), selectCurrentLine()
Parameters
  • window name:
(optional) The name of the window to stop having anything selected in. 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()

disableClickthrough

disableClickthrough(label)
Disables clickthrough for a label - making it act 'normal' again and receive clicks, doubleclicks, onEnter, and onLeave events. This is the default behaviour for labels.
See also: enableClickthrough()
Parameters
  • label:
Name of the label to restore clickability on.
Mudlet VersionAvailable in Mudlet3.17+

disableCommandLine

disableCommandLine(windowName)
Disables the command line for the miniConsole named windowName
See Also: enableCommandLine()
Parameters
  • windowName:
The name of the miniConsole to disable the command line in.
Mudlet VersionAvailable in Mudlet4.10+

disableHorizontalScrollBar

disableHorizontalScrollBar([windowName])
Disables the horizontal scroll bar for the miniConsole/userwindow windowName or the main window
See Also: enableHorizontalScrollBar()
Parameters
  • windowName:
The name of the window to disable the scroll bar in. If "main" or not provided it is the main console.
Mudlet VersionAvailable in Mudlet4.10+

disableScrollBar

disableScrollBar([windowName])
Disables the scroll bar for the miniConsole/userwindow windowName or the main window
See Also: enableScrollBar()
Parameters
  • windowName:
(optional) The name of the window to disable the scroll bar in. If "main" or not provided it is the main console.

dreplace

dreplace([window, ]text)
Replaces the output line from the game with a colour-tagged string.

See Also: decho(), dinsertText()

Parameters
  • window:
    The window to replace the selection in. Optional, defaults to the main window if not provided.
  • text:
    The text to display, as with decho()
Example
    selectCaptureGroup(1)
    dreplace("<255,0,255>[ALERT!]: <r>"..matches[2])

dreplaceLine

dreplaceLine ([window], text)
Replaces the output line from the game with a colour-tagged string.
Mudlet VersionAvailable in Mudlet4.12+

See Also: decho(), dinsertText()

Parameters
  • window (optional):
the window to copy the text from. Defaults to "main".
  • text:
    The text to display, with RGB color values inside angle brackets <>, ie <128,0,0>. If you'd like to use a background color, put it after a colon : - <:128,0,0>. You can use the <r> tag to reset to the default color.
Example
dreplaceLine("<255,0,255>[ALERT!]: <r>"..line)

echoLink

echoLink([windowName], text, command, hint, [useCurrentFormatElseDefault])
Echos a piece of text as a clickable link, at the end of the current selected line - similar to echo().
See also: cechoLink(), hechoLink()
Parameters
  • windowName:
(optional) either be none or "main" for the main console, or a miniconsole / userwindow name.
  • text:
Text to display in the echo. Same as a normal echo().
  • command:
Lua code to do when the link is clicked, as text or a function (since Mudlet 4.11).
  • hint:
Text for the tooltip to be displayed when the mouse is over the link.
  • useCurrentFormatElseDefault:
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!", function() send("hi") end, "This is a tooltip")

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
echoLink("press me!", [[send("hi")]], "This is a tooltip")

-- do the same, but send this link to a miniConsole
echoLink("my miniConsole", "press me!", function() send("hi") end, "This is a tooltip")

Note Note: The hint can contain the same sort of "rich-text" as can be used for "labels" - and if the command is set to be the empty string "" then this can be a means to show extra information for the text when the mouse is hovered over it but without a command being run should it be clicked upon, e.g.:

Screenshot showing example of fancy visual link

echoUserWindow

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

echoPopup

echoPopup([windowName], text, {commands}, {hints}, [useCurrentFormatElseDefault])
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
  • windowName:
(optional) name of the window to echo to. Use either main or omit for the main window, or the miniconsoles name otherwise.
  • text:
the text to display
  • {commands}:
a table of lua code to do, in text strings or as functions (since Mudlet 4.11), i.e. {[[send("hello")]], function() echo("hi!") end}
  • {hints}:
a table of strings which will be shown on the popup and right-click menu. i.e. {"send the hi command", "echo hi to yourself"}
  • useCurrentFormatElseDefault:
(optional) 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", {function() send "sleep" end, function() send "sit" end, function() send "stand" end}, {"sleep", "sit", "stand"})

-- alternatively, put commands as text (in [[ and ]] to use quotation marks inside)
echoPopup("activities to do", {[[send "sleep"]], [[send "sit"]], [[send "stand"]]}, {"sleep", "sit", "stand"})

enableClickthrough

enableClickthrough(label)
Make a label 'invisible' to clicks - so if you have another label underneath, it'll be clicked on instead of this one on top.
This affects clicks, double-clicks, right-clicks, as well as the onEnter/onLeave events.
See also: disableClickthrough()
Parameters
  • label:
The name of the label to enable clickthrough on.
Mudlet VersionAvailable in Mudlet3.17+

enableCommandLine

enableCommandLine(windowName)
Enables the command line for the miniConsole named windowName
See Also: disableCommandLine()
Parameters
  • windowName:
The name of the miniConsole to enable the command line in.

Note Note: The command line name is the same as the miniConsole name

Mudlet VersionAvailable in Mudlet4.10+

enableHorizontalScrollBar

enableHorizontalScrollBar([windowName])
Enables the horizontal scroll bar for the miniConsole/userwindow windowName or the main window
See Also: disableHorizontalScrollBar()
Parameters
  • windowName:
The name of the window to enable the scroll bar in. If "main" or not provided it is the main console.
Mudlet VersionAvailable in Mudlet4.10+

enableScrollBar

enableScrollBar([windowName])
Enables the scroll bar for the miniConsole/userwindow windowName or the main window
See Also: disableScrollBar()
Parameters
  • windowName:
The name of the window to enable the scroll bar in. If "main" or not provided it is the main console.

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:
(optional) name of the miniconsole to operate on. If you'd like it to work on the main window, don't specify anything or use main (since Mudlet 3.0).
  • 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")

getAvailableFonts

getAvailableFonts()
This returns a "font - true" key-value list of available fonts which you can use to verify that Mudlet has access to a given font.
To install a new font with your package, include the font file in your zip/mpackage and it'll be automatically installed for you.
See also: getFont(), setFont()
Mudlet VersionAvailable in Mudlet3.10+
Example
-- check if Ubuntu Mono is a font we can use
if getAvailableFonts()["Ubuntu Mono"] then
  -- make the miniconsole use the font at size 16
  setFont("my miniconsole", "Ubuntu Mono")
  setFontSize("my miniconsole", 16)
end

getBackgroundColor

getBackgroundColor([windowName])
Gets the background for the given label, miniconsole, or userwindow.
Returns 4 values - red, green, blue, transparency. Colors returned are from 0 to 255 (0 being black), and transparency is from 0 to 255 (0 being completely transparent).
Parameters
  • windowName:
(optional) name of the label/miniconsole/userwindow to getthe background color from, or "main" for the main window.
Mudlet VersionAvailable in Mudlet4.15+
Example
local r, g, b, a = getBackgroundColor()
local rW, gW, bW, aW = getBackgroundColor("myWindow")

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.
See also: setBgColor()
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

getBorderBottom

getBorderBottom()
Returns the size of the bottom border of the main window in pixels.
See also: getBorderSizes(), setBorderBottom()
Mudlet VersionAvailable in Mudlet4.0+
Example
setBorderBottom(150)
getBorderBottom()
-- returns: 150

getBorderLeft

getBorderLeft()
Returns the size of the left border of the main window in pixels.
See also: getBorderSizes(), setBorderLeft()
Mudlet VersionAvailable in Mudlet4.0+
Example
setBorderLeft(5)
getBorderLeft()
-- returns: 5

getBorderRight

getBorderRight()
Returns the size of the right border of the main window in pixels.
See also: getBorderSizes(), setBorderRight()
Mudlet VersionAvailable in Mudlet4.0+
Example
setBorderRight(50)
getBorderRight()
-- returns: 50

getBorderSizes

getBorderSizes()
Returns the a named table with the sizes of all borders of the main window in pixels.
See also: setBorderSizes(), getBorderTop(), getBorderRight(),getBorderBottom(), getBorderLeft()
Mudlet VersionAvailable in Mudlet4.0+
Example
setBorderSizes(100, 50, 150, 0)
getBorderSizes()
-- returns: { top = 100, right = 50, bottom = 150, left = 0 }
getBorderSizes().right
-- returns: 50

getBorderTop

getBorderTop()
Returns the size of the top border of the main window in pixels.
See also: getBorderSizes(), setBorderTop()
Mudlet VersionAvailable in Mudlet4.0+
Example
setBorderTop(100)
getBorderTop()
-- returns: 100

getClipboardText

getClipboardText()
Returns any text that is currently present in the clipboard.
See also: setClipboardText()
Note Note: Note: Available in Mudlet 4.10+
Example
local clipboardContents = getClipboardText()
echo("Clipboard: " .. clipboardContents)

getColorWildcard

getColorWildcard(ansi color number)
This function, given an ANSI color number (list), will return all strings on the current line that match it.
See also: isAnsiFgColor(), isAnsiBgColor()
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) -- this will be a table of every match

if match then -- if there's a table, then we try and print it on the screen!
  echo("\nFound "..table.concat(match, ", ").."!") -- this will combine all captured strings and separate them with a comma so it's easy to read.
else -- if there isn't something in match, then we haven't found anything to print on the screen!
  echo("\nDidn't find anyone.") 
end

getColumnCount

getColumnCount([windowName])
Gets the maximum number of columns (characters) that a given window can display on a single row, taking into consideration factors such as window width, font size, spacing, etc.
Parameters
  • windowName:
(optional) name of the window whose number of columns we want to calculate. By default it operates on the main window.
Mudlet VersionAvailable in Mudlet3.7+
Example
print("Maximum number of columns on the main window "..getColumnCount())

getColumnNumber

getColumnNumber([windowName])
Gets the absolute column number of the current user cursor.
Parameters
  • windowName:
(optional) either be none or "main" for the main console, or a miniconsole / userwindow name.

Note Note: the argument is available since Mudlet 3.0.

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([windowName])
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.
Parameters
  • windowName:
(optional) name of the window in which to select text.
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
selectString("troll",1)
local 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

getFont

getFont([windowName])
Gets the current font of the given window or console name. Can be used to get font of the main console, dockable userwindows and miniconsoles.
See also: setFont(), setFontSize(), openUserWindow(), getAvailableFonts()
Mudlet VersionAvailable in Mudlet3.4+

Note Note: Since Mudlet 3.10, returns the actual font that was used in case you didn't have the required font when using setFont().

Parameters
  • windowName:
The window name to get font size of - can either be none or "main" for the main console, or a miniconsole/userwindow name.
Example
-- The following will get the "main" console font size.
display("Font in the main window: "..getFont())

display("Font in the main window: "..getFont("main"))

-- This will get the font size of a user window named "user window awesome".
display("Font size: " .. getFont("user window awesome"))

getFontSize

getFontSize([windowName])
Gets the current font size of the given window or console name. Can be used to get font size of the Main console as well as dockable UserWindows.
See also: setFontSize(), openUserWindow()
Parameters
  • windowName:
The window name to get font size of - can either be none or "main" for the main console, or a UserWindow name.
Mudlet VersionAvailable in Mudlet3.4+
Example
-- The following will get the "main" console font size.
local mainWindowFontSize = getFontSize()
if mainWindowFontSize then
    display("Font size: " .. mainWindowFontSize)
end

local mainWindowFontSize = getFontSize("main")
if mainWindowFontSize then
    display("Font size: " .. fs2)
end

-- This will get the font size of a user window named "user window awesome".
local awesomeWindowFontSize = getFontSize("user window awesome")
if awesomeWindowFontSize then
    display("Font size: " .. awesomeWindowFontSize)
end

getHTMLformat

spanTag = getHTMLformat(formatTable)
Takes in a table of formatting options in the same style as getTextFormat() and returns a span tag which will format text after it as the table describes.
See also
getTextFormat(), getLabelFormat()
Mudlet VersionAvailable in Mudlet4.15+
Parameters
  • formatTable:
Table with formatting options configured. Keys are foreground, background, bold, underline, overline, strikeout, italic, and reverse. All except for foreground and background should be boolean (true/false) values. Foreground and background are either { r, g, b, a } tables, or strings with QSS formatting directives
Returns
  • A string with the html span tag to format text in accordance with the format table.
Example
-- Returns a span tag for bold, red text on a green background
local span = getHTMLformat({
  foreground = { 255, 0, 0 },
  background = "#00FF00",
  bold = true
})

-- span will be '<span style="color: rgb(255, 0, 0);background-color: #00FF00; font-weight: bold; font-style: normal; text-decoration: none;">'

getImageSize

getImageSize(imageLocation)
Returns the width and the height of the given image. If the image can't be found, loaded, or isn't a valid image file - nil+error message will be returned instead.
See also: createLabel()
Parameters
  • imageLocation:
Path to the image.
Mudlet VersionAvailable in Mudlet4.5+
Example
local path = getMudletHomeDir().."/my-image.png"

cecho("Showing dimensions of the picture in: "..path.."\n")

local width, height = getImageSize(path)

if not width then
  -- in case of an problem, we don't get a height back - but the error message
  cecho("error: "..height.."\n")
else
  cecho(string.format("They are: %sx%s", width, height))
end

getLabelFormat

formatTable = getLabelFormat(labelName)
Returns a format table like the one returned by getTextFormat and suitable for getHTMLformat which will format text the same way as simply doing an echo to the label would
See also
getTextFormat(), getHTMLformat()
Mudlet VersionAvailable in Mudlet4.15+
Parameters
  • labelName:
The name of the label to scan the format of
Returns
  • A table with all the formatting options to achieve a default text format for label labelName.
Example
-- creates a test label, sets a stylesheet, and then returns the default format table for that label.
createLabel("testLabel", 10, 10, 300, 200, 1)
setLabelStyleSheet([[
  color: rgb(0,0,180);
  border-width: 1px;
  border-style: solid;
  border-color: gold;
  border-radius: 10px;
  font-size: 12.0pt;
  background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #98f041, stop: 0.1 #8cf029, stop: 0.49 #66cc00, stop: 0.5 #52a300, stop: 1 #66cc00);
]])
local fmt = getLabelFormat("testLabel"))

--[[
{
  background = "rgba(0, 0, 0, 0)", -- this is transparent
  bold = false,
  foreground = "rgb(0,0,180)",
  italic = false,
  overline = false,
  reverse = false,
  strikeout = false,
  underline = false
}
--]]

getLabelSizeHint

width, height = getLabelSizeHint(labelName)
Returns the suggested labelsize as width and height
See also
getTextFormat(), getHTMLformat()
Mudlet VersionAvailable in Mudlet4.15+
Parameters
  • labelName:
The name of the label to get the suggested size from
Returns
  • suggested width and height (to fit text and/or an image on a label)
Example
-- text resizing example
-- create the label
createLabel("textLabel",400,400,300,300,1)
-- put some text on it
echo("textLabel", "This is my Test.\nAnother Test")
-- resizes the label to fit the text
resizeWindow("textLabel", getLabelSizeHint("textLabel"))

-- image resizing example
-- create the label
createLabel("imageLabel",400,400,300,300,1)
-- put some image on it
setBackgroundImage("imageLabel", getMudletHomeDir.."/myLabelImage.png")
-- resizes the label to fit the image
resizeWindow("imageLabel", getLabelSizeHint("imageLabel"))

getLabelStyleSheet

getLabelStyleSheet(labelName)
Returns the stylesheet set on a given label, which is used to customise the labels look and feel.
See also
getTextFormat()
Mudlet VersionAvailable in Mudlet4.15+
Parameters
  • labelName:
The name of the label to get the stylesheet from
Returns
  • stylesheet as a string
Example
createLabel("test", 50, 50, 100, 100, 0)
setLabelStyleSheet("test", [[
  background-color: white;
  border: 10px solid green;
  font-size: 12px;
  ]])
echo("test", "test")

-- now retrieve it and display:
local stylesheet = getLabelStyleSheet("test")
cecho(f"<green>the label's stylesheet is now: \n<white>{stylesheet}\n")

getLastLineNumber

getLastLineNumber(windowName)
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
  • windowName:
name of the window to use. Either use main for the main window, or the name of the miniconsole.
Example
-- get the latest line's # in the buffer
local latestline = getLastLineNumber("main")

getLineCount

getLineCount([windowName])
Gets the absolute amount of lines in the current console buffer
Parameters
  • windowName
Optional name of the window to get the line count of. Defaults to the main window.
Example
echo("Main window has " .. getLineCount() .. " lines of text in it.")

getLines

getLines([windowName,] 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
  • windowName
(optional) name of the miniconsole/userwindow to get lines for, or "main" for the main window (Mudlet 3.17+)
  • 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([windowName])
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
  • windowName:
(optional) name of the miniconsole to operate on. If you'd like it to work on the main window, don't specify anything.

Note Note: The argument is available since Mudlet 3.0.

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 (game output) in pixels. This also accounts for any borders that have been set.
See also: getMainWindowSize()
Parameters
None
Example
-- Save width of the main console to a variable for future use.
consoleWidth = getMainConsoleWidth()

getMouseEvents

events = getMouseEvents()
Returns a table of registered mouse events, including any of the additional arguments they may have.
Mudlet VersionAvailable in Mudlet4.13+
See also
addMouseEvent(), removeMouseEvent()
Returns
  • Returns a table with mouse event uniqueName as indexes, containing all the creation arguments as the sub-table members.

getMousePosition

getMousePosition()
Returns the coordinates of the mouse's position, relative to the Mudlet window itself.
Parameters
None
Mudlet VersionAvailable in Mudlet3.1+
Example
-- Retrieve x and y position of the mouse to determine where to create a new label, then use that position to create a new label
local x, y = getMousePosition()
createLabel("clickGeneratedLabel", x, y, 100, 100, 1)
-- if the label already exists, just move it
moveWindow("clickGeneratedLabel", x, y)
-- and make it easier to notice
setBackgroundColor("clickGeneratedLabel", 255, 204, 0, 200)

getProfileTabNumber

getProfileTabNumber()
Returns the current tab number you're in. If you have just one profile loaded, it'll always return 1 - otherwise it'll be the nth tab that is currently open.
Parameters
None
Mudlet VersionAvailable in Mudlet4.11+
Example
print(f"Current playing in tab #{getProfileTabNumber()}.")

getMainWindowSize

getMainWindowSize()
Returns two numbers, the width and height in pixels of the main window.
See also: getUserWindowSize(), setMainWindowSize(), getMainConsoleWidth()
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()

getRowCount

getRowCount([windowName])
Gets the maximum number of rows that a given window can display at once, taking into consideration factors such as window height, font type, spacing, etc.
Parameters
  • windowName:
(optional) name of the window whose maximum number of rows we want to calculate. By default it operates on the main window.
Mudlet VersionAvailable in Mudlet3.7+
Example
print("Maximum of rows on the main window "..getRowCount())

getScroll

getScroll([windowName])
Returns line that the window is currently scrolled to.
See also: scrollTo, scrollUp, scrollDown
Parameters
  • windowName:
(optional) name of the window to ask about. Default is the main window.
Mudlet VersionAvailable in Mudlet4.17.0+
Example
-- button to jump to next instance of "Timbo"
local current = getScroll()
local data = getLines(current, getLineCount())
for count, line in ipairs(data) do
  local match = string.findPattern(line, "Timbo")
  if match then
    scrollTo(current + count)
    break
  end
end

getSelection

getSelection([windowName])
Returns the text currently selected with selectString(), selectSection(), or selectCurrentLine(). Note that this isn't the text currently selected with the mouse.
Also returns the start offset and length of the selection as second and third value.
Parameters
  • windowName:
(optional) name of the window to get the selection from. By default it operates on the main window.
Mudlet VersionAvailable in Mudlet3.16+
Example
selectCurrentLine()
print("Current line contains: "..getSelection())
retrieving the selection
text,offset,len = getSelection()
-- manipulate the selection, e.g. to discover the color of characters other than the first
-- then restore it
selectSection(offset, len)

getTextFormat

getTextFormat([windowName])
Gets the current text format of the currently selected text. May be used with other console windows. The returned values come in a table containing text attribute names and their values. The values given will be booleans for: bold, italics, underline, overline, strikeout, and reverse - followed by color triplet tables for the foreground and background colors.
See Also: setTextFormat()
Parameters
  • windowName
(optional) Specify name of selected window. If no name or "main" is given, the format will be gathered from the main console.
Mudlet VersionAvailable in Mudlet3.20+
Example
-- A suitable test for getTextFormat()
-- (copy it into an alias or a script)

clearWindow()

echo("\n")

local SGR = string.char(27)..'['
feedTriggers("Format attributes: '"..SGR.."1mBold"..SGR.."0m' '"..SGR.."3mItalic"..SGR.."0m' '"..SGR.."4mUnderline"..SGR.."0m' '"..SGR.."5mBlink"..SGR.."0m' '"..SGR.."6mF.Blink"..SGR.."0m' '"..SGR.."7mReverse"..SGR.."0m' '"..SGR.."9mStruckout"..SGR.."0m' '"..SGR.."53mOverline"..SGR.."0m'.\n")

moveCursor(1,1)
selectSection(1,1)

local results = getTextFormat()
echo("For first character in test line:\nBold detected: " .. tostring(results["bold"]))
echo("\nItalic detected: " .. tostring(results["italic"]))
echo("\nUnderline detected: " .. tostring(results["underline"]))
echo("\nReverse detected: " .. tostring(results["reverse"]))
echo("\nStrikeout detected: " .. tostring(results["strikeout"]))
echo("\nOverline detected: " .. tostring(results["overline"]))
echo("\nForeground color: (" .. results["foreground"][1] .. ", " .. results["foreground"][2] .. ", " .. results["foreground"][3] .. ")")
echo("\nBackground color: (" .. results["background"][1] .. ", " .. results["background"][2] .. ", " .. results["background"][3] .. ")")

selectSection(21,1)
echo("\n\nFor individual parts of test text:")
echo("\nBold detected (character 21): " .. tostring(results["bold"]))

selectSection(28,1)
echo("\nItalic detected (character 28): " .. tostring(results["italic"]))

selectSection(37,1)
echo("\nUnderline detected (character 37): " .. tostring(results["underline"]))

selectSection(67,1)
echo("\nReverse detected (character 67): " .. tostring(results["reverse"]))

selectSection(77,1)
echo("\nStrikeout detected (character 77): " .. tostring(results["strikeout"]))

selectSection(89,1)
echo("\nOverline detected (character 89): " .. tostring(results["overline"]))
echo("\n")

getUserWindowSize

getUserWindowSize(windowName)
Returns two numbers, the width and height in pixels. This is useful for calculating the given userwindow dimensions.
See also: getMainWindowSize()
Parameters
  • windowName
the name of the userwindow we will get the dimensions from
Mudlet VersionAvailable in Mudlet4.6.1+
Example
--this will get the size of your userwindow named "ChatWindow" and save them
--into the variables mainHeight and mainWidth
mainWidth, mainHeight = getUserWindowSize("ChatWindow")

getWindowWrap

getWindowWrap(windowName)
gets at what position in the line the will start word wrap.
Parameters
  • windowName:
Name of the "main" console or user-created miniconsole which you want to be wrapped differently. If you want to wrap the main window, use windowName "main" or leave empty.
Example
setWindowWrap("main", 10)
display(getWindowWrap("main"))

-- The following output will result in the main window console:
-- 10
Practical Example
-- display ======== line with maximum possible width without wrapping
echo(string.rep("=", getWindowWrap("main")))
Mudlet VersionAvailable in Mudlet4.11+

handleWindowResizeEvent

handleWindowResizeEvent()
(deprecated) This function is deprecated 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 if Mudlet's main window is currently in focus (ie, the user isn't focused on another window, like a browser). If multiple profiles are loaded, this can also be used to check if a given profile is in focus.
Parameters
None
Example
if attacked and not hasFocus() then
  runaway()
else
  fight()
end

hecho

hecho([windowName], text)
Echoes text that can be easily formatted with colour tags in the hexadecimal format. You can also add the below tags.
Formatting
<b>  - bold
</b> - bold off
<i>  - italics
</i> - italics off
<u>  - underline
</u> - underline off
<o>  - overline
</o> - overline off
<s>  - strikethrough
</s> - strikethrough off
See Also: decho(), cecho()

Note Note: Support for labels added in Mudlet 4.15; however, it does not turn a label into a miniconsole and every time you hecho it will erase any previous echo sent to the label.

Parameters
  • windowName:
(optional) name of the window to echo to. Can either be omitted or "main" for the main window, else specify the miniconsoles name.
  • text:
The text to display, with color changes made within the string using the format |cFRFGFB,BRBGBB or #FRFGFB,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 or #r can be used within the string to reset the colors to default. Hexadecimal color codes can be found here: https://www.color-hex.com/

Note Note: Transparency for background in hex-format available in Mudlet 4.10+

Example
hecho("\n#ffffff White text!")
-- your text in white
hecho("\n#ca0004 Red text! And now reset #rit to the default color")
-- your text in red, then reset to default using #r
hecho("\n#ffffff,ca0004 White text with a red background!")
-- your text in white, against a red background
hecho("\n|c0000ff Blue text, this time using |c instead of #")
-- your text in blue, activated with |c vs #.
hecho("\n#ff0000Red text with #iitalics#/i, |uunderline|/u, #ooverline#/o, #sstrikethrough#/s, and #bbold#/b formatting.")
-- shows the various individual formatting options
hecho("\n#008000#o#uGreen text with both over and underlines.#/o#/u")

hecho2ansi

ansiFormattedString = hecho2ansi(text)
Converts hecho formatted text to ansi formatted text. Used by hfeedTriggers, but useful if you want ansi formatted text for any other reason.
See also
hecho(), hfeedTriggers()
Mudlet VersionAvailable in Mudlet4.10++

Note Note: non-color formatting added in Mudlet 4.15+

Parameters
  • text:
The hecho formatted text for conversion
Returns
  • String converted to ansi formatting
Example
-- replicates the functionality of hfeedTriggers() for a single line.
-- you would most likely just use hfeedTriggers, but it makes for a tidy example.
feedTriggers(hecho2ansi("\n#800000This is red.#r #iitalic#/i, #bbold#/b, #sstrikethrough#/s, #uunderline#/u\n"))

hechoLink

hechoLink([windowName], text, command, hint, true)
Echos a piece of text as a clickable link, at the end of the current selected line - similar to hecho(). This version allows you to use colours within your link text.
See also: cechoLink(), dechoLink()
Parameters
  • windowName:
(optional) - allows selection between sending the link to a miniconsole or the main window.
  • text:
text to display in the echo. Same as a normal hecho().
  • command:
Lua code to do when the link is clicked, as text or a function (since Mudlet 4.11).
  • hint:
text for the tooltip to be displayed when the mouse is over the link.
  • true:
requires argument for the colouring to work.
Example
-- echo a link named 'press me!' that'll send the 'hi' command to the game
hechoLink("|ca00040black!", function() send("hi") end, "This is a tooltip", true)

-- # format also works
hechoLink("#ca00040black!", function() send("hi") end, "This is a tooltip", true)

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
hechoLink("#ca00040black!", [[send("hi")]], "This is a tooltip", true)

hechoPopup

hechoPopup([windowName], text, {commands}, {hints}, [useCurrentFormatElseDefault])
Creates text with a left-clickable link, and a right-click menu for more options at the end of the current line, like hecho(). 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.
Mudlet VersionAvailable in Mudlet4.1+
Parameters
  • windowName:
(optional) name of the window to echo to. Use either main or omit for the main window, or the miniconsoles name otherwise.
  • text:
the text to display
  • {commands}:
a table of lua code to do, in text strings or as functions (since Mudlet 4.11), i.e. {[[send("hello")]], function() echo("hi!") end}
  • {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"}
  • useCurrentFormatElseDefault:
(optional) 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:
hechoPopup("#ff0000activities#r to do", {function() send "sleep" end, function() send "sit" end, function() send "stand" end}, {"sleep", "sit", "stand"}, true)

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
hechoPopup("#ff0000activities#r to do", {[[send "sleep"]], [[send "sit"]], [[send "stand"]]}, {"sleep", "sit", "stand"}, true)

hideGauge

hideGauge(gaugeName)
hides the given gauge.
See also: showGauge(), createGauge()
Parameters
  • gaugeName:
name of the gauge to show.
Example
hideGauge("my gauge")
showGauge("my gauge")

hinsertLink

hinsertLink([windowName], text, command, hint, true)
Echos a piece of text as a clickable link, at the end of the current cursor position - similar to hinsertText(). This version allows you to use colours within your link text.
See also: insertLink(), dinsertLink()
Mudlet VersionAvailable in Mudlet4.1+
Parameters
  • windowName:
optional parameter, allows selection between sending the link to a miniconsole or the main window.
  • text:
text to display in the echo. Same as a normal hecho().
  • command:
Lua code to do when the link is clicked, as text or a function (since Mudlet 4.11).
  • hint:
text for the tooltip to be displayed when the mouse is over the link.
  • true:
requires argument for the colouring to work.
Example
-- echo a link named 'press me!' that'll send the 'hi' command to the game
hinsertLink("#ff0000press #a52a2a,ffffffme!", function() send("hi") end, "This is a tooltip", true)

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
hinsertLink("#ff0000press #a52a2a,ffffffme!", [[send("hi")]], "This is a tooltip", true)

hinsertPopup

hinsertPopup([windowName], text, {commands}, {hints}, [useCurrentFormatElseDefault])
Creates text with a left-clickable link, and a right-click menu for more options at the end of the current cursor position, like hinsertText(). 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.
Mudlet VersionAvailable in Mudlet4.1+
Parameters
  • windowName:
(optional) name of the window to echo to. Use either main or omit for the main window, or the miniconsoles name otherwise.
  • text:
the text to display
  • {commands}:
a table of lua code strings to do or a functions (since Mudlet 4.11). ie, {[[send("hello")]], function() echo("hi!") end}
  • {hints}:
a table of lua code to do, in text strings or as functions (since Mudlet 4.11), i.e. {"send the hi command", "echo hi to yourself"}
  • useCurrentFormatElseDefault:
(optional) 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:
hinsertPopup("#ff0000activities#r to do", {function() send "sleep" end, function() send "sit" end, function() send "stand" end}, {"sleep", "sit", "stand"}, true)

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
hinsertPopup("#ff0000activities#r to do", {[[send "sleep"]], [[send "sit"]], [[send "stand"]]}, {"sleep", "sit", "stand"}, true)

hreplaceLine

hreplaceLine ([window], text)
Replaces the output line from the game with a colour-tagged string.
Mudlet VersionAvailable in Mudlet4.12+

See Also: hecho(), hinsertText()

Parameters
  • window (optional):
the window to copy the text from. Defaults to "main".
  • text:
    The text to display, with hex color values , ie #ff00ff. If you'd like to use a background color, put it after a comma , - #,ff99ff. You can use the #r tag to reset to the default color.
Example
hreplaceLine("#ff00ff[ALERT!]: #r"..line)

hreplace

hreplace([window, ]text)
Replaces the output line from the game with a colour-tagged string.

See Also: hecho(), hinsertText()

Parameters
  • window:
    The window to replace the selection in. Optional, defaults to the main window if not provided.
  • text:
    The text to display, as with hecho()
Example
    selectCaptureGroup(1)
    hreplace("#EE00EE[ALERT!]: #r"..matches[2])
Mudlet VersionAvailable in Mudlet4.5+

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 hide
Example
hideToolBar("my offensive buttons")

hideWindow

hideWindow(name)
This function hides a mini console, a user window or a label with the given name. To show it again, use showWindow().
See also: createMiniConsole(), createLabel(), deleteLabel()
Parameters
  • name
specifies the label or console you want to hide.
Example
function miniconsoleTest()
  local windowWidth, windowHeight = getMainWindowSize()

  -- create the miniconsole
  createMiniConsole("sys", windowWidth-650,0,650,300)
  setBackgroundColor("sys",255,69,0,255)
  setMiniConsoleFontSize("sys", 8)
  -- wrap lines in window "sys" at 40 characters per line - somewhere halfway, as an example
  setWindowWrap("sys", 40)

  print("created red window top-right")

  tempTimer(1, function()
    hideWindow("sys")
    print("hid red window top-right")
  end)

  tempTimer(3, function()
    showWindow("sys")
    print("showed red window top-right")
  end)
end

miniconsoleTest()

insertLink

insertLink([windowName], text, command, hint, [useCurrentLinkFormat])
Inserts a piece of text as a clickable link at the current cursor position - similar to insertText().
See also: echoLink(), insertText(), cinsertLink(), dinsertLink(), hinsertLink()
Parameters
  • windowName:
(optional) the window to insert the link in - use either "main" or omit for the main window.
  • text:
text to display in the window. Same as a normal echo().
  • command:
Lua code to do when the link is clicked, as text or a function (since Mudlet 4.11).
  • hint:
text for the tooltip to be displayed when the mouse is over the link.
  • useCurrentLinkFormat:
(optional) true or false. 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!", function() echo("you clicked me!\n") end, "Click me popup")

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
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!", function() echo("you clicked me!\n") end, "Click me popup", true)
resetFormat()

Note Note: The hint can contain the same sort of "rich-text" as can be used for "labels" - and if the command is set to be the empty string "" then this can be a means to show extra information for the text when the mouse is hovered over it but without a command being run should it be clicked upon, e.g.:

Screenshot showing example of fancy visual link

insertPopup

insertPopup([windowName,] text, {commands}, {hints}[, useCurrentLinkFormat])
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
  • windowName:
(optional) name of the window to echo to - use either main or omit for the main window, or the miniconsoles name otherwise.
  • text:
the text inserted for the popup to be applied to.
  • {commands}:
a table of lua code commands to do, in text strings or as functions (since Mudlet 4.11), i.e. {[[send("hello")]], function() echo("hi!") end}.
  • {hints}:
a table of strings which will be shown when the pointer hovers over the popup's text and on the right-click menu. ie, {"send the hi command", "echo hi to yourself"}.
  • useCurrentLinkFormat:
(optional) 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", {function() send "sleep" end, function() send "sit" end, function() send "stand" end}, {"sleep", "sit", "stand"})

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
insertPopup("activities to do", {[[send "sleep"]], [[send "sit"]], [[send "stand"]]}, {"sleep", "sit", "stand"})

insertText

insertText([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
  • windowName:
(optional) 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(bgColorCode)
This function tests if the first character of the current selection in the main console has the background color specified by bgColorCode.
Parameters
  • bgColorCode:
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 background color" )
end

Note Note: The variable named 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 getBgColor() and then handling the color comparison in Lua.

Also note that the color code numbers are Mudlet specific, though they do represent the colors in the 16 ANSI color-set for the main console they are not in the same order and they additionally have the default background color in the zeroth position.

isAnsiFgColor

isAnsiFgColor(fgColorCode)
This function tests if the first character of the current selection in the main console has the foreground color specified by fgColorCode.
Parameters
  • fgColorCode:
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: The variable named 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.

Also note that the color code numbers are Mudlet specific, though they do represent the colors in the 16 ANSI color-set for the main console they are not in the same order and they additionally have the default foreground color in the zeroth position.

loadWindowLayout

loadWindowLayout()
Resets the layout of userwindows (floating miniconsoles) to the last saved state.
See also: saveWindowLayout(), openUserWindow()
Mudlet VersionAvailable in Mudlet3.2+
Example
loadWindowLayout()

lowerWindow

lowerWindow(labelName)
Moves the referenced label/console below all other labels/consoles. For the opposite effect, see: raiseWindow().
Parameters
  • labelName:
the name of the label/console you wish to move below the rest.
Mudlet VersionAvailable in Mudlet3.1+
Example
createLabel("blueLabel", 300, 300, 100, 100, 1)   --creates a blue label
setBackgroundColor("blueLabel", 50, 50, 250, 255)

createLabel("redLabel", 350, 350, 100, 100, 1)    --creates a red label which is placed on TOP of the blue label, as the last made label will sit at the top of the rest
setBackgroundColor("redLabel", 250, 50, 50, 255)

lowerWindow("redLabel")                          --lowers redLabel, causing blueLabel to be back on top

moveCursor

moveCursor([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:
(optional) 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")

moveCursorDown

moveCursorDown([windowName,] [lines,] [keepHorizontal])
Moves the cursor in the given window down a specified number of lines.
See also: moveCursor(), moveCursorUp(), moveCursorEnd()
Parameters
  • windowName:
(optional) name of the miniconsole/userwindow, or "main" for the main window.
  • lines:
(optional) number of lines to move cursor down by, or 1 by default.
  • keepHorizontal:
(optional) true/false to specify if horizontal position should be retained, or reset to the start of the line otherwise.
Mudlet VersionAvailable in Mudlet3.17+
Example

Need example

moveCursorUp

moveCursorUp([windowName,] [lines,] [keepHorizontal])
Moves the cursor in the given window up a specified number of lines.
See also: moveCursor(), moveCursorDown(), moveCursorEnd()
Parameters
  • windowName:
(optional) name of the miniconsole/userwindow, or "main" for the main window.
  • lines:
(optional) number of lines to move cursor up by, or 1 by default.
  • keepHorizontal:
(optional) true/false to specify if horizontal position should be retained, or reset to the start of the line otherwise.
Mudlet VersionAvailable in Mudlet3.17+
Example

Need example

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:
(optional) name of the miniconsole/userwindow, or "main" for the main 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(), setBorderSizes(), openUserWindow()
Parameters
  • name:
The name of your window
  • newX:
The horizontal pixel location
  • newY:
The vertical pixel location

Note Note: Since Mudlet 3.7 this method can also be used on UserWindow consoles.

openUserWindow

openUserWindow(windowName, [restoreLayout], [autoDock], [dockingArea])
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 (even to a different screen on a system with a multi-screen display), dock them on any of the four sides of the main application window, make them into notebook tabs or float them.
See also: resetUserWindowTitle(), setUserWindowTitle(), saveWindowLayout(), loadWindowLayout()
Parameters
  • windowName:
name of your window, it must be unique across ALL profiles if more than one is open (for multi-playing).
  • restoreLayout: (available in Mudlet 3.2+)
(optional) - only relevant, if false is provided. Then the window won't be restored to its last known position.
  • autoDock: (available in Mudlet 4.7+)
(optional) - only relevant, if false is provided. Then the window won't dock automatically at the corners.
  • dockingArea: (available in Mudlet 4.7+)
(optional) - the area your UserWindow will be docked at. possible docking areas your UserWindow will be created in (f" floating "t" top "b" bottom "r" right and "l" left). Docking area is "right" if not given any value.

Note Note: Since Mudlet version 3.2, Mudlet will automatically remember the window's last position.

Examples
openUserWindow("My floating window")
cecho("My floating window", "<red>hello <blue>bob!")

-- if you don't want Mudlet to remember its last position:
openUserWindow("My floating window", false)

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

pauseMovie

pauseMovie(label name)
Pauses the gif animation on the label
Returns true
See also: setMovie(), startMovie(), setMovieFrame(), setMovieSpeed()
Mudlet VersionAvailable in Mudlet4.15+
Parameters
  • label name:
name of the gif label
Example
-- create a label with the name myMovie
createLabel("myMovie",0,0,200,200,0)

-- puts the gif on the label and animates it
setMovie("myMovie", getMudletHomeDir().."/movie.gif")
--stops the animation
pauseMovie("myMovie")

prefix

prefix(text, [writingFunction], [foregroundColor], [backgroundColor], [windowName])
Prefixes text at the beginning of the current line when used in a trigger.
Parameters
  • text:
the information you want to prefix
  • "writingFunction:"
optional parameter, allows the selection of different functions to be used to write the text, valid options are: echo, cecho, decho, and hecho.
  • "foregroundColor:"
optional parameter, allows a foreground color to be specified if using the echo function using a color name, as with the fg() function
  • "backgroundColor:"
optional parameter, allows a background color to be specified if using the echo function using a color name, as with the bg() function
  • "windowName:"
optional parameter, allows the selection a miniconsole or the main window for the line that will be prefixed
Example
-- Prefix the hours, minutes and seconds onto our prompt even though Mudlet has a button for that
prefix(os.date("%H:%M:%S "))
-- Prefix the time in red into a miniconsole named "my_console"
prefix(os.date("<red>%H:%M:%S<reset>", cecho, nil, nil, "my_console"))
See also: suffix()

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)

raiseWindow

raiseWindow(labelName)
Raises the referenced label/console above all over labels/consoles. For the opposite effect, see: lowerWindow().
Parameters
  • labelName:
the name of the label/console you wish to bring to the top of the rest.
Mudlet VersionAvailable in Mudlet3.1+
Example
createLabel("blueLabel", 300, 300, 100, 100, 1)   --creates a blue label
setBackgroundColor("blueLabel", 50, 50, 250, 255)

createLabel("redLabel", 350, 350, 100, 100, 1)    --creates a red label which is placed on TOP of the bluewindow, as the last made label will sit at the top of the rest
setBackgroundColor("redLabel", 250, 50, 50, 255)

raiseWindow("blueLabel")                          --raises blueLabel back at the top, above redLabel

removeCommandLineMenuEvent

removeCommandLineMenuEvent([window,] label)
Removes an existing command line menu event.
Parameters
  • window:
Window that item is associated with. Optional, defaults to "main" (main window console).
  • label:
Label under which element is registered
Returns
  • Returns True If the mouse event was removed successfully.

removeMouseEvent

removeMouseEvent(uniqueName)
Removes an existing mouse event. Returns True If the event exists and was removed successfully, throws a warning if the event doesn't exist.
Mudlet VersionAvailable in Mudlet4.13+
See also
getMouseEvents(), addMouseEvent()
Parameters
  • uniqueName:
A unique identifier that the mouse event was registered under.
Returns
  • Returns True If the mouse event was removed successfully.

replace

replace([windowName], with, [keepcolor])
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: 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.

See also: creplace

Parameters
  • windowName:
(optional) name of window (a miniconsole)
  • with:
the new text to display.
  • keepcolor:
(optional) argument, setting this to true will keep the existing colors (since Mudlet 3.0+)
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!")

replaceAll

replaceAll(what, with, [keepcolor])
Replaces all occurrences of what in the current line with with.
Parameters
  • what:
the text to replace

Note Note: This accepts Lua patterns

  • with:
the new text to have in place
  • keepcolor:
setting this to true will keep the existing colors.

Note Note: keepcolor is available in Mudlet 4.10+

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")

replaceLine

replaceLine ([window], text)
Replaces the output line from the game with your own text.

See Also: echo(), insertText()

Parameters
  • window (optional):
the window to copy the text from. Defaults to "main".
  • text:
    The text to display
Example
replaceLine("[ALERT!]: "..line)

replaceWildcard

replaceWildcard(which, replacement, [keepcolor])
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.
  • keepcolor:
setting this to true will keep the existing colors

Note Note: keepcolor available in Mudlet 4.10+

Example
replaceWildcard(2, "hello") -- on a perl regex trigger of ^You wave (goodbye)\.$, it will make it seem like you waved hello

resetCmdLineAction

resetCmdLineAction(commandLineName)
Resets the action on the command line so the it behaves like the main command line again.
Parameters
  • commandLineName
The name of the command line the action will be resetet.
See also: setCmdLineAction()
Mudlet VersionAvailable in Mudlet4.10+

resetBackgroundImage

resetBackgroundImage([windowName])
Resets the console background-image
Parameters
  • windowName
(optional) name of the console the image will be reset
See also: setBackgroundImage()
Mudlet VersionAvailable in Mudlet4.10+

resetFormat

resetFormat([windowName])
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
  • windowName
(optional) name of the console to reset formatting. Defaults to "main" if missing.
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()

resetLabelCursor

resetLabelCursor(labelName)
Resets your mouse cursor to the default one.
See also: setLabelCursor(), setLabelCustomCursor()
Mudlet VersionAvailable in Mudlet4.8+
Parameters
  • labelName: label for which to reset the cursor for.
Example
resetLabelCursor("myLabel")
-- This will reset the mouse cursor over myLabel to the default one

resetLabelToolTip

resetLabelToolTip(labelName)
Resets the tooltip on the given label.
Mudlet VersionAvailable in Mudlet4.6.1+
Parameters
  • labelName:
The name of the label the tooltip will be reseted.
See also: setLabelToolTip()

resetMapWindowTitle

resetMapWindowTitle()
resets the title of the popped out map window to default.
Mudlet VersionAvailable in Mudlet4.8+
See also: setMapWindowTitle()

resetUserWindowTitle

resetUserWindowTitle(windowName)
resets the title of the UserWindow windowName
Parameters
  • windowName:
Name of the userwindow for which the title will be resetet
Mudlet VersionAvailable in Mudlet4.8+
See also: setUserWindowTitle(), openUserWindow()

resizeWindow

resizeWindow(windowName, width, height)
Resizes a mini console, label, or floating User Windows.
See also: createMiniConsole(), createLabel(), handleWindowResizeEvent(), resizeWindow(), setBorderSizes(), openUserWindow()
Parameters
  • windowName:
The name of your window
  • width:
The new width you want
  • height:
The new height you want

Note Note: Since Mudlet 3.7 this method can also be used on User Window consoles if they are floating.

saveWindowLayout

saveWindowLayout()
Saves the layout of userwindows (floating miniconsoles), in case you'd like to load them again later.
See also: loadWindowLayout(), openUserWindow()
Mudlet VersionAvailable in Mudlet3.2+
Example
saveWindowLayout()

scaleMovie

scaleMovie(label name, [autoscale])
Resizes the gif to fill the full size of its label
See also: setMovie(), startMovie()
Parameters
  • label name:
name of the label the gif will be scaled upon
  • autoscale:
(optional) if false the gif will only be scaled once, resizing the label won't rescale the image
Mudlet VersionAvailable in Mudlet4.15+

selectCaptureGroup

selectCaptureGroup(groupNumber)
Selects the content of the capture group number in your Perl regular expression (from matches[]). Also works with named capture group. It does not work with multimatches.
See also: selectCurrentLine()
Parameters
  • groupNumberOrName:
number of the capture group you want to select, or the name of the capture group as a string
Example
--First, set a 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)

-- Or perhaps instead if you were to use "you have (?<euro>\d+) Euro"
selectCaptureGroup("euro")
fg("green")

selectCmdLineText

selectCmdLineText([commandLine])
Selects the text in your command line. You can specify which one, if you got many.
See also: createCommandLine()
Mudlet VersionAvailable in Mudlet4.13+
Parameters
  • commandLine:
(optional) name of the command line you want to have selected
Example
-- First, create an extra commandline with the following lua script:
inputContainer = inputContainer or Adjustable.Container:new({
  x = 0, y = "-4c",
  name = "InputContainer", padding = 2,
  width = "100%", height = "4c",
  autoLoad = false
})
extraCmdLine = extraCmdLine or Geyser.CommandLine:new({
  name = "extraCmdLine",
  x = 0, y = 0, width = "100%", height = "100%"
}, inputContainer)
inputContainer:attachToBorder("bottom")

-- Now you can send the following lua code with your main command line.
-- It will give 2 seconds time to click around, unselect its text, etc. before selecting its text for you:
lua tempTimer(2, function() selectCmdLineText() end)

-- This will instead select the text in the command line named extraCmdLine:
lua selectCmdLineText('extraCmdLine')

-- Same as before, but using the Geyser.CommandLine function instead:
lua extraCmdLine:selectText()

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(), selectCurrentLine(), getSelection(), getCurrentLine(), deselect()
Parameters
  • windowName:
(optional) name of the window in which to select text.
Example
-- color the whole line green!
selectCurrentLine()
fg("green")
deselect()
resetFormat()

-- to select the previous line, you can do this:
moveCursor(0, getLineNumber()-1)
selectCurrentLine()

-- to select two lines back, this:
moveCursor(0, getLineNumber()-2)
selectCurrentLine()

selectSection

selectSection( [windowName], fromPosition, length )
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.
See also: selectString(), selectCurrentLine(), getSelection()
Parameters
  • "windowName:"
(optional) name of the window in which to select text. By default the main window, if no windowName is given.
Will not work if "main" is given as the windowName to try to select from the main window.
  • fromPosition:
number to specify at which position in the line to begin selecting
  • length:
number to specify the amount of characters you want to select
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).

Note Note: You can move the user cursor with moveCursor(). When a new line arrives from the game, 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().

See also: deselect()
Parameters
  • windowName:
(optional) name of the window in which to select text. By default the main window, if no windowName or an empty string is given.
  • 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:

Example
if selectString("big monster", 1) > -1 then fg("red") end

setAppStyleSheet

setAppStyleSheet(stylesheet [, tag])
Sets a stylesheet for the entire Mudlet application and every open profile. Because it affects other profiles that might not be related to yours, it's better to use setProfileStyleSheet() instead of this function.
Raises the sysAppStyleSheetChange event which comes with two arguments in addition to the event name. The first is the optional tag which was passed into the function, or "" if nothing was given. The second is the profile which made the stylesheet changes.
See also: setProfileStyleSheet()
Parameters
  • stylesheet:
The entire stylesheet you'd like to use.
  • tag: (available in Mudlet 3.19+)
(optional) string tag or identifier that will be passed as a second argument in the sysAppStyleSheetChange event
References
See Qt Style Sheets Reference for the list of widgets you can style and CSS properties you can apply on them.
See also QDarkStyleSheet, a rather extensive stylesheet that shows you all the different configuration options you could apply, available as an mpackage here.
Example
-- credit to Akaya @ http://forums.mudlet.org/viewtopic.php?f=5&t=4610&start=10#p21770
local background_color = "#26192f"
local border_color = "#b8731b"

setAppStyleSheet([[
  QMainWindow {
     background: ]]..background_color..[[;
  }
  QToolBar {
     background: ]]..background_color..[[;
  }
  QToolButton {
     background: ]]..background_color..[[;
     border-style: solid;
     border-width: 2px;
     border-color: ]]..border_color..[[;
     border-radius: 5px;
     font-family: BigNoodleTitling;
     color: white;
     margin: 2px;
     font-size: 12pt;
  }
  QToolButton:hover { background-color: grey;}
  QToolButton:focus { background-color: grey;}
]])
Mudlet VersionAvailable in Mudlet3.0+

Note Note: Enhanced in Mudlet version 3.19.0 to generate an event that profiles/packages can utilise to redraw any parts of the UI that they themselves had previously styled so their effects can be re-applied to the new application style.

It is anticipated that the Mudlet application itself will make further use of application styling effects and two strings are provisionally planned for the second parameter in the sysAppStyleSheetChange event: "mudlet-theme-dark" and "mudlet-theme-light"; it will also set the third parameter to "system".

setBackgroundColor

setBackgroundColor([windowName], r, g, b, [transparency])
Sets the background for the given label, miniconsole, or userwindow. Colors are from 0 to 255 (0 being black), and transparency is from 0 to 255 (0 being completely transparent).
Parameters
  • windowName:
(optional) name of the label/miniconsole/userwindow to change the background color on, or "main" for the main window.
  • r:
Amount of red to use, from 0 (none) to 255 (full).
  • g:
Amount of green to use, from 0 (none) to 255 (full).
  • b:
Amount of red to use, from 0 (none) to 255 (full).
  • transparency:
(optional) amount of transparency to use, from 0 (fully transparent) to 255 (fully opaque). Defaults to 255 if omitted.

Note Note: Transparency also available for main/miniconsoles in Mudlet 4.10+

Example
-- make a red label that's somewhat transparent
setBackgroundColor("some label",255,0,0,200)

setBackgroundImage

setBackgroundImage(labelName, imageLocation)
setBackgroundImage([windowname], imageLocation, [mode])
Loads an image file (png) as a background image for a label or console. This can be used to display clickable buttons in combination with setLabelClickCallback() and such.

Note Note: You can also load images on labels via setLabelStyleSheet().

Parameters (label)
  • 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.
Parameters (consoles)
  • windowName:
(optional) name of the miniconsole/userwindow to change the background image on, or "main" for the main window.
  • 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.
  • mode:
(optional) allows different modes for drawing the background image. Possible modes areː
    • border - the background image is stretched (1)
    • center - the background image is in the center (2),
    • tile - the background image is 'tiled' (3)
    • style - choose your own background image stylesheet, see example below (4)
See also: resetBackgroundImage()
Example (label)
-- give the top border a nice look
setBackgroundImage("top bar", [[/home/vadi/Games/Mudlet/games/top_bar.png]])
Example (main/miniconsole)
-- give the main window a background image
setBackgroundImage("main", [[:/Mudlet_splashscreen_development.png]], "center")

-- or use your own for the main window:
setBackgroundImage("main", [[C:\Documents and Settings\bub\Desktop\mypicture.png]], "center")

-- give my_miniconsole a nice background image and put it in the center
setBackgroundImage("my_miniconsole", [[:/Mudlet_splashscreen_development.png]], "center")

-- give my_miniconsole a nice background image with own stylesheet option
setBackgroundImage("my_miniconsole", [[background-image: url(:/Mudlet_splashscreen_development.png); background-repeat: no-repeat; background-position: right;]], "style")

Note Note: setBackgroundImage for main/miniconsoles and userwindows available in Mudlet 4.10+

setBgColor

setBgColor([windowName], r, g, b, [transparency])
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.
If you'd like to change the background color of a window, see setBackgroundColor().
See also: cecho(), setBackgroundColor()
Parameters
  • windowName:
(optional) either be none or "main" for the main console, or a miniconsole / userwindow name.
  • 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
  • transparency:
Amount of transparency to use, from 0 (fully transparent) to 255 (fully opaque). Optional, if not used color is fully opaque


Note Note: Transparency parameter available in Mudlet 4.10+

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()

setBorderBottom

setBorderBottom(size)
Sets the size of the bottom border of the main window in pixels. A border means that the game text won't go on it, so this gives you room to place your graphical elements there.
See Also: setBorderSizes(), setBorderColor(), getBorderBottom()
Parameters
  • size:
Height of the border in pixels - with 0 indicating no border.
Example
setBorderBottom(150)

setBorderColor

setBorderColor(red, green, blue)
Sets the color of the main windows border that you can create either with lua commands, or via the main window settings.
See Also: setBorderSizes()
Parameters
  • red:
Amount of red color to use, from 0 to 255.
  • green:
Amount of green color to use, from 0 to 255.
  • blue:
Amount of blue color 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 game text won't go on it, so this gives you room to place your graphical elements there.
See Also: setBorderSizes(), setBorderColor(), getBorderLeft()
Parameters
  • size:
Width of the border in pixels - with 0 indicating no border.
Example
setBorderLeft(5)

setBorderRight

setBorderRight(size)
Sets the size of the right border of the main window in pixels. A border means that the game text won't go on it, so this gives you room to place your graphical elements there.
See Also: setBorderSizes(), setBorderColor(), getBorderRight()
Parameters
  • size:
Width of the border in pixels - with 0 indicating no border.
Example
setBorderRight(50)

setBorderSizes

setBorderSizes(top, right, bottom, left)
Sets the size of all borders of the main window in pixels. A border means that the game text won't go on it, so this gives you room to place your graphical elements there.
The exact result of this function depends on how many numbers you give to it as arguments.
See also: getBorderSizes(), setBorderTop(), setBorderRight(), setBorderBottom(), setBorderLeft(), setBorderColor()
Mudlet VersionAvailable in Mudlet4.0+
Arguments
  • setBorderSizes(top, right, bottom, left)
4 arguments: All borders will be set to their new given size.
  • setBorderSizes(top, width, bottom)
3 arguments: Top and bottom borders will be set to their new given size, and right and left will gain the same width.
  • setBorderSizes(height, width)
2 arguments: Top and bottom borders will gain the same height, and right and left borders gain the same width.
  • setBorderSizes(size)
1 argument: All borders will be set to the same size.
  • setBorderSizes()
0 arguments: All borders will be hidden or set to size of 0 = no border.
Example
setBorderSizes(100, 50, 150, 0) 
-- big border at the top, bigger at the bottom, small at the right, none at the left

setBorderSizes(100, 50, 150) 
-- big border at the top, bigger at the bottom, small at the right and the left

setBorderSizes(100, 50) 
-- big border at the top and the bottom, small at the right and the left

setBorderSizes(100) 
-- big borders at all four sides

setBorderSizes() 
-- no borders at all four sides

setBorderTop

setBorderTop(size)
Sets the size of the top border of the main window in pixels. A border means that the game text won't go on it, so this gives you room to place your graphical elements there.
See Also: setBorderSizes(), setBorderColor(), getBorderTop()
Parameters
  • size:
Height of the border in pixels - with 0 indicating no border.
Example
setBorderTop(100)

setFgColor

setFgColor([windowName], red, green, blue)
Sets the current text foreground color in the main window unless windowName parameter given.
  • windowName:
(optional) either be none or "main" for the main console, or a miniconsole / userwindow name.
  • red:
The red component of the gauge color. Passed as an integer number from 0 to 255
  • green:
The green component of the gauge color. Passed as an integer number from 0 to 255
  • blue:
The blue component of the gauge color. Passed as an integer number from 0 to 255
See also: setBgColor(), setHexFgColor(), setHexBgColor(), resetFormat()
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 )

setButtonStyleSheet

setButtonStyleSheet(button, markup)
Applies Qt style formatting to a button via a special markup language.
Parameters
  • button:
The name of the button to be formatted.
  • markup:
The string instructions, as specified by the Qt Style Sheet reference.
Note: You can instead use QWidget { markup }. QWidget will reference 'button', allowing the use of pseudostates like QWidget:hover and QWidget:selected
References
https://doc.qt.io/qt-5/stylesheet-reference.html
Example
setButtonStyleSheet("my test button", [[
  QWidget {
    background-color: #999999;
    border: 3px #777777;
  }
  QWidget:hover {
    background-color: #bbbbbb;
  }
  QWidget:checked {
    background-color: #77bb77;
    border: 3px #559955;
  }
  QWidget:hover:checked {
    background-color: #99dd99;
  } ]])

setClipboardText

setClipboardText(textContent)
Sets the value of the computer's clipboard to the string data provided.
See also: getClipboardText()
Parameters
  • textContent:
The text to be put into the clipboard.
Note Note: Note: Available in Mudlet 4.10+
Example
setClipboardText("New Clipboard Contents")
echo("Clipboard: " .. getClipboardText()) -- should echo "Clipboard: New Clipboard Contents"

setCmdLineAction

setCmdLineAction(commandLineName, luaFunctionName, [any arguments])
Specifies a Lua function to be called if the user sends text to the command line. 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 command line action. Additionally, this function passes the command line input text as the final argument.

Note Note: If no action is set the command line behaves like the main command line and sends commands directly to the game or alias engine.

The function specified in luaFunctionName is called like so:

luaFuncName(optional number of arguments, text)
See also: resetCmdLineAction()
Parameters
  • commandLineName:
The name of the command line to attach the action function to.
  • luaFunctionName:
The Lua function name to call, as a string.
  • any arguments:
(optional) Any amount of arguments you'd like to pass to the calling function.

Note Note: You can also pass a function directly instead of using a string

Mudlet VersionAvailable in Mudlet4.10+
Example
function sendTextToMiniConsole(miniConsoleName, cmdLineText)
  echo(miniConsoleName, cmdLineText.."\n")
end

setCmdLineAction("myCmdLine", "sendTextToMiniConsole", "myMiniConsole")

setCmdLineStyleSheet

setCmdLineStyleSheet([commandLineName], markup)
Applies Qt style formatting to a command line via a special markup language.
Parameters
  • commandLineName:
(optional) Name of the command line (or miniconsole the command line is in). If not given the stylesheet will be applied to the main command line.
  • markup
The string instructions, as specified by the Qt Style Sheet reference.

Note Note: Moving the command line over can adjust the other elements on the same horizontal axis, such as the search feature, buttons and network latency monitor. These additional components can take up to 30% of the screen size (400px when getMainWindowSize() was returning 1216px width). Don't go too aggressive with the numbers at first otherwise it will push elements off screen. Moving the command line over 250px on the above monitor also needed modifying of the width and max-width CSS properties. setCmdLineStyleSheet("main", [[QPlainTextEdit {margin-left: 250px; max-width: 562px; width: 562px}]])

Mudlet VersionAvailable in Mudlet4.10+
See also: enableCommandLine(), createCommandLine()
Examples
-- move the main command line over to the right
setCmdLineStyleSheet("main", [[
  QPlainTextEdit {
    margin-left: 100px; /* change 100 to your number */
    background-color: black; /* change it to your background color */
  }
]])

--only change font-size of your main command line
setCmdLineStyleSheet("main", [[
  QPlainTextEdit {
    font-sizeː20pt; 
  }
]])

--change bg/fg color of your miniconsole command line (name of the miniconsole is 'myMiniconsole'
--the command line in the miniconsole has to be enabled
setCmdLineStyleSheet("myMiniConsole", [[
  QPlainTextEdit {
    background: rgb(0,100,0);
    color: rgb(0,200,255);
    font-size: 10pt;
  }
]])

setFont

setFont(name, font)
Sets the font on the given window or console name. Can be used to change font of the main console, miniconsoles, and userwindows. Prefer a monospaced font - those work best with text games. See here for more.
See also: getFont(), setFontSize(), getFontSize(), openUserWindow(), getAvailableFonts()
Parameters
  • name:
Optional - the window name to set font size of - can either be none or "main" for the main console, or a miniconsole / userwindow name.
  • font:
The font to use.
Mudlet VersionAvailable in Mudlet3.9+
Example
-- The following will set the "main" console window font to Ubuntu Mono, another font included in Mudlet.
setFont("Ubuntu Mono")
setFont("main", "Ubuntu Mono")

-- This will set the font size of a miniconsole named "combat" to Ubuntu Mono.
setFont("combat", "Ubuntu Mono")

setFontSize

setFontSize(name, size)
Sets a font size on the given window or console name. Can be used to change font size of the Main console as well as dockable UserWindows.
See Also: getFontSize(), openUserWindow()
Parameters
  • name:
Optional - the window name to set font size of - can either be none or "main" for the main console, or a UserWindow name.
  • size:
The font size to apply to the window.
Mudlet VersionAvailable in Mudlet3.4+
Example
-- The following will set the "main" console window font to 12-point font.
setFontSize(12)
setFontSize("main", 12)

-- This will set the font size of a user window named "uw1" to 12-point font.
setFontSize("uw1", 12)

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.
See also: moveGauge(), createGauge(), setGaugeText()
Example
-- create a gauge
createGauge("healthBar", 300, 20, 30, 300, nil, "green")

--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")

setGaugeStyleSheet

setGaugeStyleSheet(gaugeName, css, cssback, csstext)
Sets the CSS stylesheets on a gauge - one on the front (the part that resizes accoding to the values on the gauge) and one in the back. You can use Qt Designer to create stylesheets.
Example
setGaugeStyleSheet("hp_bar", [[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #f04141, stop: 0.1 #ef2929, stop: 0.49 #cc0000, stop: 0.5 #a40000, stop: 1 #cc0000);
border-top: 1px black solid;
border-left: 1px black solid;
border-bottom: 1px black solid;
border-radius: 7;
padding: 3px;]],
[[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #bd3333, stop: 0.1 #bd2020, stop: 0.49 #990000, stop: 0.5 #700000, stop: 1 #990000);
border-width: 1px;
border-color: black;
border-style: solid;
border-radius: 7;
padding: 3px;]])

setGaugeText

setGaugeText(gaugename, css, ccstext )
Set the formatting of the text used inside the inserted gaugename.
Example
setGaugeText("healthBar", [[<p style="font-weight:bold;color:#C9C9C9;letter-spacing:1pt;word-spacing:2pt;font-size:12px;text-align:center;font-family:arial black, sans-serif;">]]..MY_NUMERIC_VARIABLE_HERE..[[</p>]])
Useful resources
http://csstxt.com - Generate the text exactly how you like it before pasting it into the css slot.
https://www.w3schools.com/colors/colors_picker.asp - Can help you choose colors for your text!

setHexBgColor

setHexBgColor([windowName], hexColorString)
Sets the current text background color in the main window unless windowName parameter given. This function allows to specify the color as a 6 character hexadecimal string.
  • windowName:
Optional parameter set the current text background color in windowname given.
  • hexColorString
6 character long hexadecimal string to set the color to. The first two characters 00-FF represent the red part of the color, the next two the green and the last two characters stand for the blue part of the color
See also: setBgColor(), setHexFgColor()
Example
--highlights the first occurrence of the string "Tom" in the current line with a red Background color.
selectString( "Tom", 1 )
setHexBgColor( "FF0000" )

setHexFgColor

setHexFgColor([windowName], hexColorString)
Sets the current text foreground color in the main window unless windowName parameter given. This function allows to specify the color as a 6 character hexadecimal string.
  • windowName:
Optional parameter set the current text foreground color in windowname given.
  • hexColorString
6 character long hexadecimal string to set the color to. The first two characters 00-FF represent the red part of the color, the next two the green and the last two characters stand for the blue part of the color
See also: setFgColor(), setHexBgColor()
Example
--highlights the first occurrence of the string "Tom" in the current line with a red foreground color.
selectString( "Tom", 1 )
setHexFgColor( "FF0000" )

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.

setLabelToolTip

setLabelToolTip(labelName, text, [duration])
Sets a tooltip on the given label.
Mudlet VersionAvailable in Mudlet4.6.1+
Parameters
  • labelName:
The name of the label to set the tooltip to.
  • text:
The text to be shown. Can contain Qt rich text formats.
  • duration:
Duration of the tooltip timeout in seconds. Optional, if not set the default duration will be set.
See also: resetLabelToolTip()

setLabelClickCallback

setLabelClickCallback(labelName, luaFunctionName, [any 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. Additionally, this function passes an event table as the final argument. This table contains information about the mouse button clicked, other buttons that were pressed at the time, and the mouse cursor's local (relative to the label) and global (relative to the Mudlet window) position. The function specified in luaFunctionName is called like so:
luaFuncName(optional number of arguments, event)

where event has the following structure:

event = {
  x = 100,
  y = 200,
  globalX = 300,
  globalY = 320,
  button = "LeftButton",
  buttons = {"RightButton", "MidButton"},
}
See also: setLabelDoubleClickCallback(), setLabelReleaseCallback(), setLabelMoveCallback(), setLabelWheelCallback(),setLabelOnEnter(), setLabelOnLeave()
Parameters
  • labelName:
The name of the label to attach a callback function to.
  • luaFunctionName:
Lua function to call, or the function name, as a string.
  • any arguments:
(optional) Any amount of arguments you'd like to pass to the calling function.

Note Note: Event argument is available in 3.6+, and in 4.8+ you can pass a function directly instead of a string.

Note Note: While event.button may contain a single string of any listed below, event.buttons will only ever contain some combination of "LeftButton", "MidButton", and "RightButton"

The following mouse button strings are defined:
"LeftButton"        "RightButton"        "MidButton"
"BackButton"        "ForwardButton"      "TaskButton"
"ExtraButton4"      "ExtraButton5"       "ExtraButton6"
"ExtraButton7"      "ExtraButton8"       "ExtraButton9"
"ExtraButton10"     "ExtraButton11"      "ExtraButton12"
"ExtraButton13"     "ExtraButton14"      "ExtraButton15"
"ExtraButton16"     "ExtraButton17"      "ExtraButton18"
"ExtraButton19"     "ExtraButton20"      "ExtraButton21"
"ExtraButton22"     "ExtraButton23"      "ExtraButton24"
Example
createLabel("testLabel", 50, 50, 100, 100, 0)

function onClickGoNorth(event)
  if event.button == "LeftButton" then
    send("walk north")
  elseif event.button == "RightButton" then
    send("swim north")
  elseif event.button == "MidButton" then
    send("gallop north")
  end
end

setLabelClickCallback("testLabel", "onClickGoNorth")

-- you can also use them within tables:
mynamespace =
  {
    onClickGoNorth =
      function()
        echo("the north button was clicked!")
      end,
  }
setLabelClickCallback("testLabel", "mynamespace.onClickGoNorth")

-- or by passing the function directly:
setLabelClickCallback("testLabel", onClickGoNorth)

setLabelDoubleClickCallback

setLabelDoubleClickCallback(labelName, luaFunctionName, [any arguments])
Specifies a Lua function to be called if the user double 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. Additionally, this function passes an event table as the final argument, as in setLabelClickCallback()
Mudlet VersionAvailable in Mudlet3.6+
See also: setLabelClickCallback(), setLabelReleaseCallback(), setLabelMoveCallback(), setLabelWheelCallback(), 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.
  • any arguments:
(optional) Any amount of arguments you'd like to pass to the calling function.

setLabelMoveCallback

setLabelMoveCallback(labelName, luaFunctionName, [any arguments])
Specifies a Lua function to be called when the mouse moves while inside the specified label/console. 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. Additionally, this function passes an event table as the final argument, as in setLabelClickCallback()
See Also: setLabelClickCallback(), setLabelDoubleClickCallback(), setLabelReleaseCallback(), setLabelWheelCallback(), 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.
  • any arguments:
(optional) Any amount of arguments you'd like to pass to the calling function.
Mudlet VersionAvailable in Mudlet3.6+

setLabelOnEnter

setLabelOnEnter(labelName, luaFunctionName, [any 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. Additionally, this function passes an event table as the final argument, similar to setLabelClickCallback(), but with slightly different information.
For this callback, the event argument has the following structure:
event = {
  x = 100,
  y = 200,
  globalX = 300,
  globalY = 320,
}
See Also: setLabelClickCallback(), setLabelDoubleClickCallback(), setLabelReleaseCallback(), setLabelMoveCallback(), setLabelWheelCallback(), 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).
  • any arguments:
(optional) Any amount of 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

setLabelOnLeave(labelName, luaFunctionName, [any 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).
  • any arguments:
(optional) Any amount of 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" )

setLabelReleaseCallback

setLabelReleaseCallback(labelName, luaFunctionName, [any arguments])
Specifies a Lua function to be called when a mouse click ends that originated on the specified label/console. This function is called even if you drag the mouse off of the label/console before releasing the click. 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. Additionally, this function passes an event table as the final argument, as in setLabelClickCallback()
Mudlet VersionAvailable in Mudlet3.0+
See Also: setLabelClickCallback(), setLabelDoubleClickCallback(), setLabelMoveCallback(), setLabelWheelCallback(), 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.
  • any arguments:
(optional) Any amount of arguments you'd like to pass to the calling function.

Note Note: The event argument only available since Mudlet 3.6

Example
function onReleaseNorth()
  echo("the north button was released!")
end

setLabelReleaseCallback( "compassNorthImage", "onReleaseNorth" )

-- you can also use them within tables:
mynamespace = {
  onReleaseNorth = function()
    echo("the north button was released!")
  end
}

setLabelReleaseCallback( "compassNorthImage", "mynamespace.onReleaseNorth" )

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.
Note that when specifying a file path for styling purposes, forward slashes, / , must be used, even if your OS uses backslashes, \ , normally.
References
https://doc.qt.io/qt-5/stylesheet-reference.html
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");
  ]])
--This creates a label whose background changes when the users mouse hovers over it.

--putting the styleSheet in a variable allows us to easily change the styleSheet. We also are placing colors in variables that have been preset.  
local labelBackgroundColor = "#123456"
local labelHoverColor = "#654321"
local labelFontSize = 12
local labelName = "HoverLabel"
local ourLabelStyle = [[
QLabel{
	background-color: ]]..labelBackgroundColor..[[;
	font-size: ]]..labelFontSize..[[px;
	qproperty-alignment: 'AlignCenter | AlignCenter';
}
QLabel::hover{
	background-color: ]]..labelHoverColor..[[;
	font-size: ]]..labelFontSize..[[px;
	qproperty-alignment: 'AlignCenter | AlignCenter';
}
]]

--Creating the label using the labelName and ourLabelStyle variables created above.
createLabel(labelName,0,0,400,400,1)
setLabelStyleSheet(labelName, ourLabelStyle)
echo("HoverLabel","This text shows while mouse is or is not over the label.")
--Using QLabel::hover mentioned above. Lets "trick" the label into changing it's text.
--Please keep in mind that the setLabelMoveCallback allows for much more control over not just your label but your entire project.

--putting the styleSheet in a variable allows us to easily change the styleSheet. We also are placing colors in variables that have been preset.  
local labelBackgroundColor = "#123456"
local labelHoverColor = "#654321"
local labelFontSize = 12
local labelName = "HoverLabel"
--Notice we are adding a string returned from a function. In this case, the users profile directory.
local ourLabelStyle = [[
QLabel{
	border-image: url("]]..getMudletHomeDir()..[[/imagewithtext.png");
}
QLabel::hover{
	border-image: url("]]..getMudletHomeDir()..[[/imagewithhovertext.png");
}
]]

--Creating the label using the labelName and ourLabelStyle variables created above.
createLabel(labelName,0,0,400,400,1)
setLabelStyleSheet(labelName, ourLabelStyle)
--This is just to example that echos draw on top of the label. You would not want to echo onto a label you were drawing text on with images, because echos would draw on top of them.
echo("HoverLabel","This text shows while mouse is or is not over the label.")

setLabelCursor

setLabelCursor(labelName, cursorShape)
Changes how the mouse cursor looks like when over the label. To reset the cursor shape, use resetLabelCursor().
See also: resetLabelCursor(), setLabelCustomCursor()
Mudlet VersionAvailable in Mudlet4.8+
Parameters
  • labelName:
Name of the label which you want the mouse cursor change at.
  • cursorShape
Shape of the mouse cursor. List of possible cursor shapes is available here.
Example
setLabelCursor("myLabel", "Cross")
-- This will change the mouse cursor to a cross if it's over the label myLabel

setLabelCustomCursor

setLabelCustomCursor(labelName, custom cursor, [hotX, hotY])
Changes the mouse cursor shape over your label to a custom cursor. To reset the cursor shape, use resetLabelCursor().
See also: resetLabelCursor(), setLabelCursor()
Mudlet VersionAvailable in Mudlet4.8+
Parameters
  • labelName:
Name of the label which you want the mouse cursor change at.
  • custom cursor
Location of your custom cursor file. To be compatible with all systems it is recommended to use png files with size of 32x32.
  • hotX
X-coordinate of the cursors hotspot position. Optional, if not set it is set to -1 which is in the middle of your custom cursor.
  • hotY
Y-coordinate of the cursors hotspot position. Optional, if not set it is set to -1 which is in the middle of your custom cursor.
Example
setLabelCustomCursor("myLabel", getMudletHomeDir().."/custom_cursor.png")
-- This will change the mouse cursor to your custom cursor if it's over the label myLabel

setLabelWheelCallback

setLabelWheelCallback(labelName, luaFunctionName, [any arguments])
Specifies a Lua function to be called when the mouse wheel is scrolled while inside the specified label/console. 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. Additionally, this function passes an event table as the final argument, similar to setLabelClickCallback(), but with slightly different information.
For this callback, the event argument has the following structure:
event = {
  x = 100,
  y = 200,
  globalX = 300,
  globalY = 320,
  buttons = {"RightButton", "MidButton"},
  angleDeltaX = 0,
  angleDeltaY = 120
}
Keys angleDeltaX and angleDeltaY correspond with the horizontal and vertical scroll distance, respectively. For most mice, these values will be multiples of 120.
See Also: setLabelClickCallback(), setLabelDoubleClickCallback(), setLabelReleaseCallback(), setLabelMoveCallback(), 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.
  • any arguments:
(optional) Any amount of arguments you'd like to pass to the calling function.
Mudlet VersionAvailable in Mudlet3.6+
Example
function onWheelNorth(event)
  if event.angleDeltaY > 0 then
    echo("the north button was wheeled forwards over!")
  else
    echo("the north button was wheeled backwards over!")
  end
end

setLabelWheelCallback( "compassNorthImage", "onWheelNorth" )

-- you can also use them within tables:
mynamespace = {
  onWheelNorth = function()
    echo("the north button was wheeled over!")
  end
}

setWheelReleaseCallback( "compassNorthImage", "mynamespace.onWheelNorth" )

setLink

setLink([windowName], 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
  • windowName:
(optional) name of a miniconsole or a userwindow in which to select the text in.
  • command:
command to do when the text is clicked, as text or Lua function.
  • 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!
-- perl 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()

-- 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!")

setMainWindowSize

setMainWindowSize(mainWidth, mainHeight)
Changes the size of your main Mudlet window to the values given.
See Also: getMainWindowSize()
Parameters
  • mainWidth:
The new width in pixels.
  • mainHeight:
The new height in pixels.
Example
--this will resize your main Mudlet window
setMainWindowSize(1024, 768)

setMapWindowTitle

setMapWindowTitle(text)
Changes the title shown in the mapper window when it's popped out.
See also: resetMapWindowTitle()
Parameters
  • text:
New window title to set.
Mudlet VersionAvailable in Mudlet4.8+
Example
setMapWindowTitle("my cool game map")

setMiniConsoleFontSize

setMiniConsoleFontSize(name, fontSize)
Sets the font size of the mini console. see also: setFontSize(), createMiniConsole(), createLabel()

setMovie

setMovie(label name, path to gif)
Adds a gif to the selected label and animates it. Note that gifs are pretty expensive to play, so don't add too many at once.
Some websites you can get gifs from are Tenor and Giphy (not officially endorsed).
Returns true
See also: startMovie(), pauseMovie(), setMovieFrame(), setMovieSpeed()
Mudlet VersionAvailable in Mudlet4.15+
Parameters
  • label name:
name of the label the gif will be animated on
  • path:
path of the gif file
Example
-- download & show a gif within mudlet
local saveto = getMudletHomeDir().."/kymip.gif"
-- animation credit to https://opengameart.org/content/kymiball-ii-third-prototype-scraps
local url = "https://opengameart.org/sites/default/files/kymip_0.gif"

if downloadHandler then killAnonymousEventHandler(downloadHandler) end
downloadHandler = registerAnonymousEventHandler("sysDownloadDone",
  function(_, filename)
    if filename ~= saveto then
      return true
    end
    
    local width, height = getImageSize(saveto)

    createLabel("kymip", 300, 300, width, height, 0)
    setMovie("kymip", saveto)
    setLabelReleaseCallback("kymip", function() deleteLabel("kymip") end)
  end, true)

downloadFile(saveto, url)
local gifpath = getMudletHomeDir().."/movie.gif"

local width, height = getImageSize(gifpath)

-- create a label with the name mygif
createLabel("mygif", 0, 0, width, height,0)
-- put the gif on the label and animate it
setMovie("mygif", gifpath)

setMovieFrame

setMovieFrame(label name, frame nr)
Jump to a specific frame in the gif.
Returns true if successful, and false if frame doesn't exist.
See also: setMovie(), startMovie(), pauseMovie(), setMovieSpeed()
Mudlet VersionAvailable in Mudlet4.15+
Parameters
  • label name:
name of the gif label
  • frame nr:
the gif animations frame nr to jump to
Example
-- create a label with the name myMovie
createLabel("myMovie",0,0,200,200,0)

-- puts the gif on the label and animates it
setMovie("myMovie", getMudletHomeDir().."/movie.gif")
--stops the animation
pauseMovie("myMovie")
-- jumps to frame 12 of the animation
setMovieFrame("myMovie", 12)
--start the animation
startMovie("myMovie")

setMovieSpeed

setMovieSpeed(label name, speed in percent)
Set the animation speed, in percent.
Returns true
See also: setMovie(), startMovie(), pauseMovie(), setMovieFrame()
Mudlet VersionAvailable in Mudlet4.15+
Parameters
  • label name:
name of the gif label
  • speed in percent:
the gif animations speed in percent for example 50 for 50% speed
Example
-- create a label with the name myMovie
createLabel("myMovie",0,0,200,200,0)

-- puts the gif on the label and animates it
setMovie("myMovie", getMudletHomeDir().."/movie.gif")
--accelerates the animation to a speed of 150%
setMovieSpeed("myMovie",150)

setOverline

setOverline([windowName], boolean)
Sets the current text font to be overlined (true) or not overlined (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 overlined. Any text you add after with echo() or insertText() will be overlined until you use resetFormat().
  • windowName:
(optional) name of the window to set the text to be overlined or not.
  • boolean:
A true or false that enables or disables overlining of text
Example
-- enable overlined text
setOverline(true)
-- the following echo will be have an overline
echo("hi")
-- turns off bolding, italics, underlines, colouring, and strikethrough (and, after this and reverse have been added, them as well). 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()
Mudlet VersionAvailable in Mudlet3.17+

setPopup

setPopup([windowName], {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
  • windowName:
the name of the console to operate on. If not using this in a miniConsole, use "main" as the name.
This argument was ignored before Mudlet 4.11.
  • {lua code}:
a table of lua code to do, in text strings or as functions (since Mudlet 4.11), i.e. {[[send("hello")]], function() echo("hi!") end}
  • {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", {function() send("bye") end, function() echo("hi!") end}, {"send 'bye' to the MUD", "click to echo 'hi!'"})

-- alternatively, put command as text (in [[ and ]] to use quotation marks inside)
setPopup("main", {[[send("bye")]], [[echo("hi!")]]}, {"send 'bye' to the MUD", "click to echo 'hi!'"})

setProfileStyleSheet

setProfileStyleSheet(stylesheet)
Sets a stylesheet for the current Mudlet profile - allowing you to customise content outside of the main window (the profile tabs, the scrollbar, and so on). This function is better than setAppStyleSheet() because it affects only the current profile and not every other one as well.
See also: setAppStyleSheet()
Parameters
  • stylesheet:
The entire stylesheet you'd like to use. See Qt Style Sheets Reference for the list of widgets you can style and CSS properties you can apply on them.
See also QDarkStyleSheet, a rather extensive stylesheet that shows you all the different configuration options you could apply, available as an mpackage here.
Example
-- credit to Akaya @ http://forums.mudlet.org/viewtopic.php?f=5&t=4610&start=10#p21770
local background_color = "#26192f"
local border_color = "#b8731b"

setProfileStyleSheet([[
  QMainWindow {
     background: ]]..background_color..[[;
  }
  QToolBar {
     background: ]]..background_color..[[;
  }
  QToolButton {
     background: ]]..background_color..[[;
     border-style: solid;
     border-width: 2px;
     border-color: ]]..border_color..[[;
     border-radius: 5px;
     font-family: BigNoodleTitling;
     color: white;
     margin: 2px;
     font-size: 12pt;
  }
  QToolButton:hover { background-color: grey;}
  QToolButton:focus { background-color: grey;}

  QTreeView {
     background: ]]..background_color..[[;
     color: white;
  }

  QMenuBar{ background-color: ]]..background_color..[[;}

  QMenuBar::item{ background-color: ]]..background_color..[[;}

  QDockWidget::title {
     background: ]]..border_color..[[;
  }
  QStatusBar {
     background: ]]..border_color..[[;
  }
  QScrollBar:vertical {
     background: ]]..background_color..[[;
     width: 15px;
     margin: 22px 0 22px 0;
  }
  QScrollBar::handle:vertical {
     background-color: ]]..background_color..[[;
     min-height: 20px;
     border-width: 2px;
     border-style: solid;
     border-color: ]]..border_color..[[;
     border-radius: 7px;
  }
  QScrollBar::add-line:vertical {
   background-color: ]]..background_color..[[;
   border-width: 2px;
   border-style: solid;
   border-color: ]]..border_color..[[;
   border-bottom-left-radius: 7px;
   border-bottom-right-radius: 7px;
        height: 15px;
        subcontrol-position: bottom;
        subcontrol-origin: margin;
  }
  QScrollBar::sub-line:vertical {
   background-color: ]]..background_color..[[;
   border-width: 2px;
   border-style: solid;
   border-color: ]]..border_color..[[;
   border-top-left-radius: 7px;
   border-top-right-radius: 7px;
        height: 15px;
        subcontrol-position: top;
        subcontrol-origin: margin;
  }
  QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {
     background: white;
     width: 4px;
     height: 3px;
  }
  QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
     background: none;
  }
]])

-- if you'd like to reset it, use:
setProfileStyleSheet("")

-- to only affect scrollbars within the main window and miniconsoles, prefix them with 'TConsole':
setProfileStyleSheet[[
  TConsole QScrollBar:vertical {
      border: 2px solid grey;
      background: #32CC99;
      width: 15px;
      margin: 22px 0 22px 0;
  }
  TConsole QScrollBar::handle:vertical {
      background: white;
      min-height: 20px;
  }
  TConsole QScrollBar::add-line:vertical {
      border: 2px solid grey;
      background: #32CC99;
      height: 20px;
      subcontrol-position: bottom;
      subcontrol-origin: margin;
  }
  TConsole QScrollBar::sub-line:vertical {
      border: 2px solid grey;
      background: #32CC99;
      height: 20px;
      subcontrol-position: top;
      subcontrol-origin: margin;
  }
  TConsole QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {
      border: 2px solid grey;
      width: 3px;
      height: 3px;
      background: white;
  }
  TConsole QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
      background: none;
  }
]]
Mudlet VersionAvailable in Mudlet4.6+

setReverse

setReverse([windowName], boolean)
Sets the current text to swap foreground and background color settings (true) or not (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 have it's colors swapped. Any text you add after with echo() or insertText() will have their foreground and background colors swapped until you use resetFormat().
  • windowName:
(optional) name of the window to set the text colors to be reversed or not.
  • boolean:
A true or false that enables or disables reversing of the fore- and back-ground colors of text
Example
-- enable fore/back-ground color reversal of text
setReverse(true)
-- the following echo will have the text colors reversed
echo("hi")
-- turns off bolding, italics, underlines, colouring, and strikethrough (and, after this and overline have been added, them as well). 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()
Mudlet VersionAvailable in Mudlet3.17+

Note Note: Although the visual effect on-screen is the same as that of text being selected if both apply to a piece of text they neutralise each other - however the effect of the reversal will be carried over in copies made by the "Copy to HTML" and in logs made in HTML format log file mode.

setStrikeOut

setStrikeOut([windowName], boolean)
Sets the current text font to be striken out (true) or not striken out (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 striken out until you use resetFormat().
  • windowName:
(optional) name of the window to set the text to be stricken out or not.
  • boolean:
A true or false that enables or disables striking out of text
Example
-- enable striken-out text
setStrikeOut(true)
-- the following echo will be have a strikethrough
echo("hi")
-- turns off bolding, italics, underlines, colouring, and strikethrough. 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()

setTextFormat

setTextFormat(windowName, r1, g1, b1, r2, g2, b2, bold, underline, italics, [strikeout], [overline], [reverse])
Sets current text format of selected window. This is a more convenient means to set all the individual features at once compared to using setFgColor(windowName, r,g,b), setBold(windowName, true), setItalics(windowName, true), setUnderline(windowName, true), setStrikeOut(windowName, true).
See Also: getTextFormat()
Parameters
  • windowName
Specify name of selected window. If empty string "" or "main" format will be applied to the main console
  • r1,g1,b1
To color text background, give number values in RBG style
  • r2,g2,b2
To color text foreground, give number values in RBG style
  • bold
To format text bold, set to 1 or true, otherwise 0 or false
  • underline
To underline text, set to 1 or true, otherwise 0 or false
  • italics
To format text italic, set to 1 or true, otherwise 0 or false
  • strikeout
(optional) To strike text out, set to 1 or true, otherwise 0 or false or simply no argument
  • overline
(optional) To use overline, set to 1 or true, otherwise 0 or false or simply no argument
  • reverse
(optional) To swap foreground and background colors, set to 1 or true, otherwise 0 or false or simply no argument
Example
--This script would create a mini text console and write with bold, struck-out, 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,true,0,false,1);
echo("con1","This is a test")

Note Note: In versions prior to 3.7.0 the error messages and this wiki were wrong in that they had the foreground color parameters as r1, g1 and b1 and the background ones as r2, g2 and b2.

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.

setUserWindowTitle

setUserWindowTitle(windowName, text)
sets a new title text for the UserWindow windowName
Parameters
  • windowName:
Name of the userwindow
  • text
new title text
Mudlet VersionAvailable in Mudlet4.8+
See also: resetUserWindowTitle(), openUserWindow()

setUserWindowStyleSheet

setUserWindowStyleSheet(windowName, markup)
Applies Qt style formatting to the border/title area of a userwindow via a special markup language.
Parameters
  • windowName:
Name of the userwindow
  • markup
The string instructions, as specified by the Qt Style Sheet reference.
Note that when you dock the userwindow the border style is not provided by this
Mudlet VersionAvailable in Mudlet4.10+
Example
-- changes the title area style of the UserWindow 'myUserWindow'
setUserWindowStyleSheet("myUserWindow", [[QDockWidget::title{ 
    background-color: rgb(0,255,150);
    border: 2px solid red;
    border-radius: 8px;
    text-align: center;    
    }]])
See also: openUserWindow()

setWindow

setWindow(windowName, name, [Xpos, Ypos, show])
Changes the parent window of an element.
Mudlet VersionAvailable in Mudlet4.8+
Parameters
  • windowName:
Name of the userwindow which you want the element put in. If you want to put the element into the main window, use windowName "main".
  • name
Name of the element which you want to switch the parent from. Elements can be labels, miniconsoles and the embedded mapper. If you want to move the mapper use the name "mapper"
  • Xpos:
X position of the element. Measured in pixels, with 0 being the very left. Passed as an integer number. Optional, if not given it will be 0.
  • Ypos:
Y position of the element. Measured in pixels, with 0 being the very top. Passed as an integer number. Optional, if not given it will be 0.
  • show:
true or false to decide if the element will be shown or not in the new parent window. Optional, if not given it will be true.
Example
setWindow("myuserwindow", "mapper")
-- This will put your embedded mapper in your userwindow "myuserwindow".

setWindowWrap

setWindowWrap(windowName, wrapAt)
sets at what position in the line the will start word wrap.
Parameters
  • windowName:
Name of the "main" console or user-created miniconsole which you want to be wrapped differently. If you want to wrap the main window, use windowName "main".
  • wrapAt:
Number of characters at which the wrap must happen at the latest. This means, it probably will be wrapped earlier than that.
Example
setWindowWrap("main", 10)
display("This is just a test")

-- The following output will result in the main window console:
"This is
just a
test"

setWindowWrapIndent

setWindowWrapIndent(windowName, wrapTo)
sets how many spaces wrapped text will be indented with (after the first line of course).
Parameters
  • windowName:
Name of the "main" console or user-created miniconsole which you want to be wrapped differently. If you want to wrap the main window, use windowName "main".
  • wrapTo:
Number of spaces which wrapped lines are prefixed with.
Example
setWindowWrap("main", 10)
setWindowWrapIndent("main", 3)
display("This is just a test")

-- The following output will result in the main window console:
"This is
   just a
   test"

showCaptureGroups

showCaptureGroups()
Lua debug function that highlights in random colors 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 DebugTools.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. This function is defined in DebugTools.lua.
Example

See How to use multimatches[n][m] for a more thorough explanation including examples.

showWindow

showWindow(name)
Makes a hidden window (label or miniconsole) be shown again.
See also: hideWindow()

startMovie

startMovie(label name)
Starts the gif animation - if it was previously stopped or paused.
Returns true
See also: setMovie(), pauseMovie(), setMovieFrame(), setMovieSpeed()
Mudlet VersionAvailable in Mudlet4.15+
Parameters
  • label name:
name of the gif label
Example
-- create a label with the name myMovie
createLabel("myMovie",0,0,200,200,0)

-- puts the gif on the label and animates it
setMovie("myMovie", getMudletHomeDir().."/movie.gif")
--stops the animation
pauseMovie("myMovie")
--restart the animation
startMovie("myMovie")

showColors

showColors([columns], [filterColor], [sort])
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:
(optional) number of columns to print the color table in.
  • filterColor:
(optional) filter text. If given, the colors displayed will be limited to only show colors containing this text.
  • sort:
(optional) sort colors alphabetically.
Example
-- display as four columns:
showColors(4)

-- show only red colours:
showColors("red")

The output for this is:

showColors(4)

showGauge

showGauge(gaugeName)
shows the given gauge, in case it was hidden previously.
See also: hideGauge(), createGauge()
Parameters
  • gaugeName:
name of the gauge to show.
Example
hideGauge("my gauge")
showGauge("my gauge")

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 attack buttons")

suffix

suffix(text, [writingFunction], [foregroundColor], [backgroundColor], [windowName])
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.
Parameters
  • text
the information you want to prefix
  • writingFunction
optional parameter, allows the selection of different functions to be used to write the text, valid options are: echo, cecho, decho, and hecho.
  • foregroundColor
optional parameter, allows a foreground color to be specified if using the echo function using a color name, as with the fg() function
  • backgroundColor
optional parameter, allows a background color to be specified if using the echo function using a color name, as with the bg() function
  • windowName
optional parameter, allows the selection a miniconsole or the main window for the line that will be prefixed
See also: prefix(), echo()

setCommandBackgroundColor

setCommandBackgroundColor([windowName], r, g, b, [transparency])
Sets the background color for echo of commands. Colors are from 0 to 255 (0 being black), and transparency is from 0 to 255 (0 being completely transparent).
Parameters
  • windowName:
(optional) name of the label/miniconsole/userwindow to change the background color on, or "main" for the main window.
  • r:
Amount of red to use, from 0 (none) to 255 (full).
  • g:
Amount of green to use, from 0 (none) to 255 (full).
  • b:
Amount of red to use, from 0 (none) to 255 (full).
  • transparency:
(optional) amount of transparency to use, from 0 (fully transparent) to 255 (fully opaque). Defaults to 255 if omitted.
Mudlet VersionAvailable in Mudlet4.17.0+
Example
-- make a red command background color in main console.
setCommandBackgroundColor(255,0,0,200)

setCommandForegroundColor

setCommandForegroundColor([windowName], r, g, b, [transparency])
Sets the foreground color for echo of commands. Colors are from 0 to 255 (0 being black), and transparency is from 0 to 255 (0 being completely transparent).
Parameters
  • windowName:
(optional) name of the label/miniconsole/userwindow to change the background color on, or "main" for the main window.
  • r:
Amount of red to use, from 0 (none) to 255 (full).
  • g:
Amount of green to use, from 0 (none) to 255 (full).
  • b:
Amount of red to use, from 0 (none) to 255 (full).
  • transparency:
(optional) amount of transparency to use, from 0 (fully transparent) to 255 (fully opaque). Defaults to 255 if omitted.
Mudlet VersionAvailable in Mudlet4.17.0+
Example
-- make a red command foreground color in main console.
setCommandForegroundColor(255,0,0,200)

scrollDown

scrollDown([windowName,] [lines])
Scrolls down in window by a certain number of lines.
See also: getScroll, scrollTo, scrollUp
Parameters
  • windowName:
(optional) name of the window in which to scroll. Default is the main window.
  • lines:
(optional) how many lines to scroll by. Default is 1.
Mudlet VersionAvailable in Mudlet4.17.0+
Example
-- scroll down by 7 lines
scrollDown(7)

scrollUp

scrollUp([windowName,] [lines])
Scrolls up in window by a certain number of lines.
See also: getScroll, scrollTo, scrollDown
Parameters
  • windowName:
(optional) name of the window in which to scroll. Default is the main window.
  • lines:
(optional) how many lines to scroll by. Default is 1.
Mudlet VersionAvailable in Mudlet4.17.0+
Example
-- scroll up by 7 lines
scrollUp(7)

scrollTo

scrollTo([windowName,] [lineNumber])
Scrolls window to a specific line in the buffer.
Parameters
  • windowName:
(optional) name of the window in which to scroll. Default is the main window.
  • lineNumber:
(optional) target line to scroll to, counting from the top of buffer or with negative numbers to count from the end of buffer. Default is the end of the buffer, to stop scrolling.
See also: getScroll, scrollUp, scrollDown
Mudlet VersionAvailable in Mudlet4.17.0+
Example
-- scroll to line 42 in buffer
scrollTo(42)

-- start of session
scrollTo(0)

-- 20 lines ago
scrollTo(-20)

-- chat window to line 30
scrollTo("chat", 30)

-- stop scrolling main window
scrollTo()

-- stop scrolling chat window
scrollTo("chat")

windowType

typeOfWindow = windowType(windowName)
Given the name of a window, will return if it's a label, miniconsole, userwindow or a commandline.
See also
createLabel(), openUserWindow()
Mudlet VersionAvailable in Mudlet4.15+
Parameters
  • windowName:
The name used to create the window element. Use "main" for the main console


Returns
  • Window type as string ("label", "miniconsole", "userwindow", or "commandline") or nil+error if it does not exist.
Example
-- Create a Geyser label and and check its type
testLabel = Geyser.Label:new({name = "testLabel"})
display(windowType(testLabel.name))  -- displays "label"

-- the main console returns "miniconsole" because it uses the same formatting functions
display(windowType("main")) -- displays "miniconsole"

-- check for the existence of a window
local windowName = "this thing does not exist"
local ok, err = windowType(windowName)
if ok then
  -- do things with it, as it does exist.
  -- the ok variable will hold the type of window it is ("label", "commandline", etc)
else
  cecho("<red>ALERT!! window does not exist")
end
Additional development notes

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())


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.

spairs

spairs(tbl, sortFunction)
Returns an iterator similar to pairs(tbl) but sorts the keys before iterating through them.
Parameters
  • tbl:
The table to iterate over
  • sortFunction:
The function to use for determining what order to iterate the items in the table. Defaults to alphanumeric sorting by key. Similar to table.sort. See example for more info.
Mudlet VersionAvailable in Mudlet4.10+
Example
local tbl = { Tom = 40, Mary = 50, Joe = 23 }

-- This iterates, sorting based on the key (which is the name in this case)
for name, thingies in spairs(tbl) do
  echo(string.format("%s has %d thingies\n", name, thingies))
end
--[[
Joe has 23 thingies
Mary has 50 thingies
Tom has 40 thingies
--]]

-- The function used below sorts based on the value. 
for name, thingies in spairs(tbl, function(t,a,b) return t[a] < t[b] end) do --iterate from lowest value to highest
  echo(string.format("%s has %d thingies\n", name, thingies))
end
--[[
Joe has 23 thingies
Tom has 40 thingies
Mary has 50 thingies
--]]

-- This function can be used to sort a group of Geyser gauges based on their value (what percentage of the gauge is filled)
local gaugeSort = function(t,a,b)
    local avalue = t[a].value or 100 -- treat non-gauges as though they are full gauges. If you know for -sure- the table only has gauges the 'or 100' is not needed.
    local bvalue = t[b].value or 100
    return avalue < bvalue
end
for _,gauge in spairs(tblOfGauges, gaugeSort) do
  -- do what you want with the gauges. First one will be the least full, then the next least full, until the last which will be the most full. 
  -- If you replace the < with a > it will go from most full to least full instead.
end

table.collect

table.collect(tbl, func)
Returns a table that is every key-value pair from tbl for which func(key,value) returns true
Parameters
  • tbl:
The table to collect items from
  • func:
the function to use for testing if an item should be collected or not
Mudlet VersionAvailable in Mudlet4.8+
Example
local vitals = { hp = 3482, maxhp = 5000, mana = 3785, maxmana = 5000 }
local pullHpKeys = function(key, value)
  if string.match(key, "hp") then return true end
end
local hp_values = table.collect(vitals, pullHpKeys)
display(hp_values)

This prints the following:

{
  hp = 3482,
  maxhp = 5000
}
Returns
A table containing all the key/value pairs from tbl that cause func(key,value) to return true

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:
Example
local t1 = {key = 1,1,2,3}
local t2 = {key = 2,1,1,1}
local comp = table.complement(t1,t2)
display(comp)

This prints the following:

  key = 1,
  [2] = 2,
  [3] = 3
Returns
A table containing all the key/value pairs from table1 that do not match the key/value pairs from 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 as of Mudlet 4.8+).
Returns true or false
See also
table.index_of

Note Note: This tests for the 'value' parameter as either a key or value in the table. That means this will return true: table.contains({"Bob"}, 1)

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

-- if the table has just a few values, you can skip making a local, named table:
if table.contains({"Anna", "Alanna", "Hanna"}, "Anna") then 
   print("Have 'Anna' in the list!")
else
   print("Don't have the name. Sorry!")
end

-- don't forget, it will return true if the item is a key in the table as well
display(table.contains({"bob"}, 1) -- displays true, as 1 is the key/index for "bob"
-- If you really only want to check values, try table.index_of, which returns the key a value is found at, or nil if it is not found.

table.deepcopy

table.deepcopy (table)
Returns a complete copy of the table.
Parameters
  • table:
The table which you'd like to get a copy of.
Example
local test_table = { "value1", "value2", "value3", "value4" }

-- by just doing:
local newtable = test_table
-- you're linking newtable to test_table. Any change in test_table will be reflected in newtable.

-- however, by doing:
local newtable = table.deepcopy(test_table)
-- the two tables are completely separate now.

table.intersection

table.intersection (set1, set2)
Returns a table that is the relative intersection of the first table with respect to the second table. Returns a intersection of key/value pairs.
Parameters
  • table1:
  • table2:
Example
local t1 = {key = 1,1,2,3}
local t2 = {key = 1,1,1,1}
local intersect = table.intersection(t1,t2)
display(intersect)

This prints the following:

  key = 1,
  1
Returns
A table containing all the key/value pairs from table1 that match the key/value pairs from table2.

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*.
Examples
--it will insert whats inside the variable of matches[2] into at the end of table of 'test_db_name'. 
table.insert(test_db_name, matches[2])
--it will insert other thing at the first position of this table.
table.insert(test_db_name, 1, "jgcampbell300")

--[=[

This results:

test_db_name = {
    "jgcampbell300",
    "SlySven"
}
]=]

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. Think of it as a table.find function (although it is called table.index_of).

Parameters
  • table:
The table in which you are searching 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.keys

table.keys(table)
return a table that is the collection of the keys in use by the table passed in
Parameters
  • table:
The table you are collecting keys from.
Mudlet VersionAvailable in Mudlet4.1+
Example
   local testTable = {
     name = "thing",
     type = "test",
     malfunction = "major"
   }
   local keys = table.keys(testTable)
   -- key is now a table { "name", "type", "malfunction" } but the order cannot be guaranteed
   -- as pairs() does not iterate in a guaranteed order. If you want the keys in alphabetical
   -- run table.sort(keys) and keys == { "malfunction", "name", "type" }

table.load

table.load(location, table)
Load a table from an external file into mudlet.
See also: table.save

Tip: you can load a table from anywhere on your computer, but it's preferable to have them consolidated somewhere connected to Mudlet, such as the current profile.

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 {}
if io.exists(getMudletHomeDir().."/mytable.lua") then
  table.load(getMudletHomeDir().."/mytable.lua", mytable) -- using / is OK on Windows too.
end

table.matches

table.matches(tbl, pattern, [pattern2], [pattern_n], [check_keys])
Returns a table of key-value pairs from tbl which match one of the supplied patterns when checked via string.match. This function is not recursive - nested tables within tbl will not be checked, only the top-level.
Parameters
  • tbl:
the table you want to check over using string.match
  • pattern:
the pattern you want to use to check each key-value pair. You may specify multiple patterns, separated by commas
  • check_keys:
boolean argument, set to true if you want to include a key-value pair if the key or value string.matches. If you do not set this, only the value will be checked
Mudlet VersionAvailable in Mudlet4.8+
Example
local items = { this = "that", hp = 400, [4] = "toast", something = "else", more = "keypairs" }
local matches = table.matches(items, "%d")
-- here matches will be { hp = 400 }
local matches = table.matches(items, "%d", "that", true)
-- here matches will be { hp = 400, this = "that", [4] = "toast" }

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_collect

table.n_collect(tbl, func(value))
returns a table which contains every unique value from tbl for which func(value) returns true. Ignores keys. Table returned is ipairs iterable.
Parameters
  • tbl:
the table you want to collect values from
  • func(value):
the function to check each value against
Mudlet VersionAvailable in Mudlet4.8+
Example
local items = { 
  this = "that",
  other = "thing",
  otter = "potato",
  honey = "bee"
}
local beginsWithTH = function(value)
  if string.match(value, "^th") then return true end
end
local nmatches = table.n_collect(items, beginsWithTH)
-- nmatches will be { "that", "thing" }
-- the order will not necessarily be preserved

table.n_filter

table.n_filter(table, function(element[, index[, table]]))
Returns a new table with all elements that pass the test implemented by the provided function. If no elements pass the test, an empty table will be returned.
Parameters
  • table: the table you wish to filter values out of.
  • function: the function to test each element of the array. Return true to keep the element, false otherwise. It accepts three arguments:
    • element: The current element being processed in the table.
    • index: (optional) The index of the current element being processed in the table.
    • table: (optional) The table n_filter was called upon.
Examples

Filter out small values:

local function isBigEnough(value) return value >= 10 end
local filtered = table.n_filter({12, 5, 8, 130, 44}, isBigEnough)
-- filtered: {12, 130, 44}

Filter out invalid entries:

local invalidEntries = 0
local entries = {
  { id = 15 }, { id = -1 }, { id = 0 }, { id = 3 },
  { id = 12.2 }, { }, { id = nil }, { id = false },
  { id = 'not a number' }
}

local function isNumber(t) return t and type(t) == 'number' end
local function filterByID(item)
  if isNumber(item.id) and item.id ~= 0 then
    return true
  end
  invalidEntries = invalidEntries + 1
  return false
end

local entriesByID = table.n_filter(entries, filterByID)
-- invalidEntries: 5
-- entriesByID: { { id = 15 }, { id = -1 }, { id = 3 }, { id = 12.2 } }

Filter out content based on search criteria:

local fruits = {'apple', 'banana', 'grapes', 'mango', 'orange'}
local function filterItems(t, query)
  return table.n_filter(t, function(item)
    return item:lower():find(query:lower())
  end)
end
filterItems(fruits, 'ap') -- {'apple', 'grapes'}
filterItems(fruits, 'an') -- {'banana', 'mango', 'orange'}

table.n_flatten

table.n_flatten(table)
Returns a new table with the sub-table elements concatenated into it.
Parameters
  • table: A table of nested sub-tables you wish to flatten.
Example
local t1 = {1, 2, {3, 4}};
local t2 = {1, 2, {3, 4, {5, 6}}};
local t3 = {1, 2, {3, 4, {5, 6, {7, 8, {9, 10}}}}};
table.n_flatten(t1) -- {1, 2, 3, 4}
table.n_flatten(t2) -- {1, 2, 3, 4, 5, 6}
table.n_flatten(t3) -- {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

table.n_matches

table.n_matches(tbl, pattern, [pattern2], [patternN])
Returns a table of unique values within tbl which one of the supplied patterns matches using string.match
Parameters
  • tbl:
The table you want to search for values
  • pattern:
The pattern you want to check each value with, using string.match. You can supply multiple patterns, separated by commas
Mudlet VersionAvailable in Mudlet4.8+
Example
local items = { this = "that", [4] = "other", hp = 500, mana = 40 }
local matches = table.n_matches(items, "%a")
-- matches will be { "that", "other" }
-- order is not preserved/guaranteed

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

table.n_complement (set1, set2)
Returns a table that is the relative complement of the first numerically indexed table with respect to the second numerically indexed table. Returns a numerically indexed complement of values.
Parameters
  • table1:
  • table2:
Example
local t1 = {1,2,3,4,5,6}
local t2 = {2,4,6}
local comp = table.n_complement(t1,t2)
display(comp)

This prints the following:

  1,
  3,
  5
Returns
A table containing all the values from table1 that do not match the values from table2.

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
Example
local t1 = {1,2,3,4,5,6}
local t2 = {2,4,6}
local intersect = table.n_intersection(t1,t2)
display(intersect)

This prints the following:

  2,
  4,
  6
Returns
A table containing the values that are found in every one of the tables.

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.
See https://www.lua.org/pil/19.3.html for more info

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.update(table1, table2)
Returns a table in which key/value pairs from table2 are added to table1, and any keys present in both tables are assigned the value from table2, so that the resulting table is table1 updated with information from table2.
Example
display(table.update({a = 1, b = 2, c = 3}, {b = 4, d = 5}))
{
   a = 1,
   b = 4,
   c = 3,
   d = 5
}

-- to just set a table to new values, assign it directly:
mytable = {key1 = "newvalue"}

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,
}

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

<lua> --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" </lua>

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 that numerical codes are not necessarily portable across platforms.
See also: string.byte
Example

<lua> --The following call will return the string "ABC" corresponding to the ASCII values 65, 66, 67 mystring = string.char(65, 66, 67)

</lua>

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

<lua> --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 .. "'") </lua>

string.dump

string.enclose

string.enclose(String)
Wraps a string with [[ ]]
Returns the altered string.
Parameters
  • String: The string to enclose. Passed as a string.
Example

<lua> --This will echo 'Oh noes!' to the main window echo("'" .. string.enclose("Oh noes!") .. "'") </lua>

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

<lua> --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 </lua>

string.find

string.findPattern

string.findPattern(text, pattern)
Return first matching substring or nil.
Parameters
text:
pattern:
Example

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

   local match = string.findPattern("Troll is here!", "Troll")
   if match then
   echo("I did find: " .. match)
   end

</lua> This example will find substring regardless of case. <lua>local match = string.findPattern("Troll is here!", string.genNocasePattern("troll")) if match then echo("I did find: " .. match) end </lua>

  • Return value:
nil or first matching substring

See also: string.genNocasePattern()

string.format

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.

<lua>echo(string.genNocasePattern("123abc"))</lua>

  • Return value:
case insensitive pattern string

string.gfind

string.gmatch

string.gsub

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.

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

string.match

string.rep

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

string.reverse

string.reverse(String)
mystring:reverse()
Returns a string that is the string String reversed.
Example

<lua> mystring = "Hello from Lua" echo(mystring:reverse()) -- displays 'auL morf olleH' </lua>

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.
Example

<lua> -- 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) </lua>

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

<lua> --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 </lua>

string.sub

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

<lua> --Variable testname is now Anna. testname = string.title("anna") --Example will set test to "Bob". test = "bob" test = test:title() </lua>

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

<lua> --This will print 'Troll is here!', without the extra spaces. local str = string.trim(" Troll is here! ") echo("'" .. str .. "'") </lua>

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.
See also: string.lower

Mudlet Object Functions

disableAlias

disableAlias(name)
Disables/deactivates the alias by it’s name. If several aliases have this name, they’ll all be disabled.
Parameters
  • name:
The name of the alias. Passed as a string.
Examples

<lua> --Disables the alias called 'my alias' disableAlias("my alias") </lua>

disableKey

disableKey(name)
Disable key or key group "name" (hot keys or action keys).
Parameters
  • name:
The name or the id returned by tempTimer to identify the key or group name that you want to disable.
Examples

Need example use

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

<lua> --Disables the timer called 'my timer' disableTimer("my timer") </lua>

disableTrigger

disableTrigger(name)
Disables a trigger that was previously enabled.
Parameters
  • name:
Expects the trigger ID that was returned by tempTrigger on creation of the timer or the name of the timer in case of a GUI trigger.
Example

<lua> -- Disables the trigger called 'my trigger' disableTrigger("my trigger") </lua>

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

<lua> --Enables the alias called 'my alias' enableAlias("my alias") </lua>

enableKey

enableKey(name)
Enable key or key group "name" (hot keys or action keys).
Parameters
  • name:
The name or the id returned by tempTimer to identify the key or group name that you want to enable.

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.

<lua> --Enables the timer called 'my timer' enableTimer("my timer") </lua>

enableTrigger

enableTrigger(name)
Enables a Trigger. see enableTimer for more details.

<lua> enableTrigger("my trigger") </lua>

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

<lua> echo("I have " .. exists("my trigger", "trigger") .. " triggers called 'my trigger'!") </lua>

You can also use this alias to avoid creating duplicate things, for example:

<lua> -- 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 </lua>

getButtonState

getButtonState()
This function can only be used inside a toggle button script
Returns 2 if button is checked, and 1 if it's not.
Example

<lua> checked = getButtonState(); if checked == 1 then

   hideExits()

else

   showExits()

end; </lua>

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

<lua> 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 </lua>

isActive

isActive(name, type)
You can use this function to check if something, or somethings, are active.
Parameters
  • name:
The name or the id returned by tempTimer to identify the item.
  • type:
The type can be 'alias', 'trigger', or 'timer'.
Example

<lua> echo("I have " .. isActive("my trigger", "trigger") .. " currently active trigger(s) called 'my trigger'!") </lua>

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

<lua> -- make a trigger pattern with 'Lua function', and this will trigger on every prompt! return isPrompt() </lua>

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.

<lua> --Deletes the alias called 'my alias' killAlias("my alias") </lua>

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 to turn them on or off.

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 timer id doesn’t exist anymore (timer has already fired) or the timer is not a temp timer.

killTrigger

killTrigger(id)
Deletes a tempTrigger.
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

<lua> -- 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.")) </lua>

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.

<lua> --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 </lua>

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

<lua> -- 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])]] </lua> 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.

setConsoleBufferSize

setConsoleBufferSize( consoleName, linesLimit, sizeOfBatchDeletion )
Sets the maximum number of lines can 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

<lua> -- sets the main windows size to 5 million lines maximum - which is more than enough! setConsoleBufferSize("main", 5000000, 1000) </lua>

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

<lua> -- 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! </lua>

tempAlias

tempAlias(regex, code to do)
Creates a temporary alias - it'll won't be saved when Mudlet restarts and thus wiped.
Parameters
  • regex: Alias pattern in regex.
  • code to do::The code to do when the timer is up - wrap it in [[ ]], or provide a Lua function.
Examples

<lua> tempAlias("^hi$", send ("hi") echo ("we said hi!") </lua>

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.
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

<lua> 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 </lua>

Examples

<lua> -- 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");]] ); </lua>

tempTimer

tempTimer(time, code to do)
Creates a temporary single shot timer and returns the timer ID for subsequent enableTimer, disableTimer and killTimer calls. You can use 2.3 seconds or 0.45 etc. After it has fired, the timer will be deactivated and killed.
Parameters
  • time: The time in seconds for which to set the timer for.
  • code to do: The code to do when the timer is up - wrap it in [[ ]], or provide a Lua function.
Examples

<lua> -- 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) </lua>

Note Note: [[ ]] 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. Also note that the 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:

<lua> 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) </lua>

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:

<lua> mudlet = mudlet or {}; mudlet.mapper_script = true </lua>


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

<lua> 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 </lua>

addRoom

addRoom(roomID)

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

See also: createRoomID

<lua> local newroomid = createRoomID() addRoom(newroomid) </lua>

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

<lua> -- 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) </lua>

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

<lua> clearRoomUserData(341) </lua>

clearSpecialExits

clearSpecialExits(roomID)

Removes all special exits from a room.

See also: addSpecialExit

<lua> clearSpecialExits(1337)

if #getSpecialExits(1337) == 0 then -- clearSpecialExits will neve fail on a valid room ID, this is an example

 echo("All special exits successfully cleared from 1337.\n")

end </lua>

createMapLabel

labelID = createMapLabel(areaID, text, posx, posy, fgRed, fgGreen, fgBlue, bgRed, bgGreen, bgBlue)

Creates a visual label on the map for all z-levels at given coordinates, with the given background and foreground colors. 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

<lua> local labelid = createMapLabel( 50, "my map label", 0, 0, 255,0,0,23,0,0) </lua>

createMapper

createMapper(x, y, width, height)

Creates a miniconsole window for mapper to render in, the with the given dimensions. You can only create one at a time at the moment.

<lua> 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 </lua>

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

<lua> deleteArea(23) </lua>

deleteMapLabel

deleteMapLabel(areaID, labelID)

Deletes a map label from a specfic area.

See also: createMapLabel

<lua> deleteMapLabel(50, 1) </lua>

deleteRoom

deleteRoom(roomID)

Deletes an individual room, and unlinks all exits leading to and from it.

<lua> deleteRoom(335) </lua>

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 that on Mudlet versions prior to the 2.0 final release, this function would raise an error.

<lua> -- 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 </lua>

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.

<lua> -- 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 </lua>

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.

<lua> {

 envid1 = {r,g,b},
 envid2 = {r,g,b}

} </lua>

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.

<lua> display(getMapLabels(43)) table {

 0: 
 1: 'Svorai's grove'

}

deleteMapLabel(43, 0) display(getMapLabels(43)) table {

 1: 'Svorai's grove'

} </lua>

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.

<lua> -- 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 </lua>

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 that if the room ID does not exist, this function will raise an error

<lua> display("Area ID of room #100 is: "..getRoomArea(100))

display("Area name for room #100 is: "..getRoomAreaName(getRoomArea(100))) </lua>

getRoomAreaName

areaname = getRoomAreaName(areaID)

Returns the area name for a given area id.

<lua> echo(string.format("room id #455 is in %s.", getRoomAreaName(getRoomArea(455)))) </lua>

getRoomCoordinates

x,y,z = getRoomCoordinates(room ID)

Returns the room coordinates of the given room ID.

<lua> local x,y,z = getRoomCoordinates(roomID) echo("Room Coordinates for "..roomID..":") echo("\n X:"..x) echo("\n Y:"..y) echo("\n Z:"..z) </lua>

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.

<lua> funtion checkID(id)

 echo(strinf.format("The env ID of room #%d is %d.\n", id, getRoomEnv(id)))

end </lua>

getRoomExits

getRoomExits (roomID) Returns the currently known non-special exits for a room in an key-index form: exit = exitroomid, ie:

<lua> table {

 'northwest': 80
 'east': 78

} </lua>

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.

<lua> -- 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 </lua>

getRoomName

roomName = getRoomName(roomID)

Returns the room name for a given room id.

<lua> echo(string.format("The name of the room id #455 is %s.", getRoomname(455)) </lua>

getRooms

rooms = getRooms()

Returns the list of all rooms in the map in an area in roomid - room name format.

<lua> -- simple, raw viewer for rooms in an area display(getRooms()) </lua>

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.

<lua> -- sample script 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

</lua>

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 for setting the user data.

<lua> display(getRoomUserData(341, "visitcount")) </lua>

getRoomWeight

room weight = getRoomWeight(roomID)

Returns the weight of a room. By default, all new rooms have a weight of 1.

See also: setRoomWeight

<lua> display("Original weight of room 541: "..getRoomWeight(541) setRoomWeight(541, 3) display("New weight of room 541: "..getRoomWeight(541) </lua>

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.

<lua> getSpecialExits(1337)

-- results in: --[[ table {

 12106: 'faiglom nexus'

} ]] </lua>

getSpecialExitsSwap

exits = getSpecialExitsSwap(roomID)

Very similar to getSpecialExits, 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
 }

Examples

<lua> -- check if the east exit of room 1201 is locked display(hasExitLock(1201, 4)) </lua>

See also: lockExit

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

Available since Mudlet 2.0 final release

<lua> -- 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) </lua>

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
 }

Examples

<lua> -- lock the east exit of room 1201 so we never path through it lockExit(1201, 4, true) </lua>

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

<lua> 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. </lua>

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

<lua> echo(string.format("Is room #4545 locked? %s.", roomLocked(4545) and "Yep" or "Nope")) </lua>

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.

<lua> local savedok = saveMap(getMudletHomeDir().."/my fancy map.dat") if not savedok then

 echo("Couldn't save :(\n")

else

 echo("Saved fine!\n")

end </lua>

searchRoom

searchRoom (room name)

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, like so:

<lua> 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'

} ]]</lua>

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

setAreaName

setAreaName(areaID, newName)

Renames an existing area to the new name.

<lua> setAreaName(2, "My city") </lua>

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.

<lua> 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 </lua>

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.

Returns false if the exit creation didn't work.

<lua> -- alias pattern: ^exit (\d+) (\w+)$

if setExit(mmp.currentroom, tonumber(matches[2]),matches[3]) then echo("\nExit set to room:"..matches[2]..", Direction:"..string.upper(matches[3])) centerview(mmp.currentroom) else mmp.echo("Failed to set the exit.") end </lua>

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.

<lua> -- locate the room on the other end, so we can unlink it from there as well if necessary local otherroom if getRoomExits(getRoomExits(mmp.currentroom)[dir])[mmp.ranytolong(dir)] then

 otherroom = getRoomExits(mmp.currentroom)[dir]

end

if setExit(mmp.currentroom, -1, dir) then

 if otherroom then
   if setExit(otherroom, -1, mmp.ranytolong(dir)) then
     mmp.echo(string.format("Deleted the %s exit from %s (%d).",
       dir, getRoomName(mmp.currentroom), mmp.currentroom))
    else mmp.echo("Couldn't delete the incoming exit.") end
 else
   mmp.echo(string.format("Deleted the one-way %s exit from %s (%d).",
     dir, getRoomName(mmp.currentroom), mmp.currentroom))
 end

else

 mmp.echo("Couldn't delete the outgoing exit.")

end </lua>

You can use these numbers for setting the directions as well: <lua> 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

}</lua>

setGridMode

setGridMode(area, 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.

<lua> setGridMode(55,true) -- set area with ID 55 to be in grid mode </lua>

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.

<lua> setRoomChar(431, "#")

setRoomChar(123. "$") </lua>

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.

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

<lua> -- 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) </lua>

You can make them relative as well:

<lua> -- 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) </lua>

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.

<lua> setRoomEnv(551, 34) -- set room with the ID of 551 to the environment ID 34 </lua>

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.

<lua> setRoomName(534, "That evil room I shouldn't visit again.") lockRoom(534, true) -- and lock it just to be safe </lua>

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

<lua> -- 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) </lua>

setRoomWeight

setRoomWeight(roomID, weight)

Sets a weight to the given roomID. By default, all rooms have a weight of 0 - 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.

To completely avoid a room, make use of lockRoom().

See also: getRoomWeight

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

unHighlightRoom

unHighlightRoom(roomID)

Unhighlights a room if it was previously highlighted and restores the rooms original environment color.

See also: highlightRoom

Available since Mudlet 2.0 final release

<lua> unHighlightRoom(4534) </lua>

Miscellaneous Functions

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.

<lua> expandAlias("t rat")

expandAlias("t rat", false) </lua>

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.

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.

<lua> -- ask it to display a table display({a = "somevalue", 1,2,3}) -- or some other target display(target) </lua>

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.

<lua> -- 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) </lua>

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.

<lua> -- turn prompt flags on: sendTelnetChannel102("\52\1")

-- turn prompt flags off: sendTelnetChannel102("\52\2") </lua>

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.

<lua> -- 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" </lua>

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.

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.

<lua> if io.exists("/home/vadi/Desktop") then

 echo("This folder exists!")

else

 echo("This folder doesn't exist.")

end

if io.exists("/home/vadi/Desktop/file.tx") then

 echo("This file exists!")

else

 echo("This file doesn't exist.")

end </lua>

spawn

t = 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().

<lua> -- 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() </lua>

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.
Requires Mudlet 2.0+
Example

<lua> -- 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 </lua>

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

<lua> --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"}]]) </lua>

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

<lua> --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") </lua>

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

<lua> -- 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(getMuldetHomeDir().. /mypackage/boingboing.wav) </lua>

disconnect

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

<lua> disconnect() </lua>

reconnect

reconnect()
Force-reconnects (so if you're connected, it'll disconnect) you to the game.
Example

<lua> -- you could trigger this on a log out message to reconnect, if you'd like reconnect() </lua>

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

<lua> showColors(4) </lua> The output for this is:

showColors(4)

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

<lua> %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. </lua>


Database Functions

These database functions make using a database with Mudlet easier. They are in addition to the LuaSQL sqlite driver that's available directly within Mudlet (also see the LuaSQL manual for comparison).

For a tutorial on how to get started with the database functions, see here.

db:add

db:add(sheet reference, table1, …, tableN)
Adds one or more new rows to the specified sheet. If any of these rows would violate a UNIQUE index, a lua error will be thrown and execution will cancel. As such it is advisable that if you use a UNIQUE index, you test those values before you attempt to insert a new row.
Returns nil plus the error message if the operation failed (so it won't raise a runtime error in Mudlet).
Example
--Each table is a series of key-value pairs to set the values of the sheet, 
--but if any keys do not exist then they will be set to nil or the default value.
db:add(mydb.enemies, {name="Bob Smith", city="San Francisco"})
db:add(mydb.enemies,
     {name="John Smith", city="San Francisco"},
     {name="Jane Smith", city="San Francisco"},
     {name="Richard Clark"})
--As you can see, all fields are optional.

-- example that'll show an error if things went wrong:
local ok, err = db:add(mydb.enemies, {name="Bob Smith", city="San Francisco"})
if not ok then
  debugc(f"Error adding to the database: {err}")
  return
end

db:aggregate

db:aggregate(field reference, aggregate function, query, distinct)
Returns the result of calling the specified aggregate function on the field and its sheet. The query is optional.
The supported aggregate functions are:
  • COUNT - Returns the total number of records that are in the sheet or match the query.
  • AVG - Returns the average of all the numbers in the specified field.
  • MAX - Returns the highest number in the specified field.
  • MIN - Returns the lowest number in the specified field.
  • TOTAL - Returns the value of adding all the contents of the specified field.

Note Note: You can supply a boolean true for the distinct argument since Mudlet 3.0 to filter by distinct values.

Example
local mydb = db:get_database("my database")
echo(db:aggregate(mydb.enemies.name, "count"))
It can also be used in conjunction with db:like to return a number of results.
Example
local query = matches[2]
local mydb = db:get_database("itemsdab")
local results = db:aggregate(mydb.itemstats.objname, "count", db:like(mydb.itemstats.objname, "%" .. query .. "%"))
cecho("Found <red>"..results.."<reset> items that match the description.")

db:AND

db:AND(sub-expression1, …, sub-expressionN)
Returns a compound database expression that combines all of the simple expressions passed into it; these expressions should be generated with other db: functions such as db:eq, db:like, db:lt and the like.
This compound expression will only find items in the sheet if all sub-expressions match.

db:between

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

db:close

db:close(database name)
Closes a database connection so it can't be used anymore.

db:create

db:create(database name, schema table, force)
Creates and/or modifies an existing database. This function is safe to define at a top-level of a Mudlet script: in fact it is recommended you run this function at a top-level without any kind of guards as it will also open and return a reference to the database. If the named database does not exist it will create it. If the database does exist then it will add any columns or indexes which didn’t exist before to that database. If the database already has all the specified columns and indexes, it will do nothing. If an existing column with at least one non-NULL value is missing from the new schema, it will raise an error by default; the user may force the dropping of the column by setting the force argument to true.
The database will be called Database_<sanitized database name>.db and will be stored in the Mudlet configuration directory within your profile folder, which you can find with getMudletHomeDir().

Note Note: Known bug! This function will accept characters other than a-z, but will convert uppercase characters to lower and strip any others including numbers. For example "My DB" and "my-db_2024-07-09" would both result in a database simply named "mydb", as you can imagine this can lead to unexpected behaviour. In order to preserve backward compatibility, there is currently no intention to fix this.

Database tables are called sheets consistently throughout this documentation, to avoid confusion with Lua tables.
The schema table must be a Lua table array containing table dictionaries that define the structure and layout of each sheet. The starting Lua type will determine the type in the database, i.e. if you want to store text set it to = "" and if you want to store a number set it to = 0.
Example
local mydb = db:create("combatLog",
  {
    kills = {
              name = "",
              area = "",
              killed = db:Timestamp("CURRENT_TIMESTAMP"),
              damage = 0,
              _index = { {"name", "area"} }
            },
    enemies = {
                name = "",
                city = "",
                reason = "",
                enemied = db:Timestamp("CURRENT_TIMESTAMP"),
                _index = { "city" },
                _unique = { "name" },
                _violations = "IGNORE"
               }
  })
The above will create a database with two sheets; the first is kills and is used to track every successful kill, with both where and when the kill happened. It has one index, a compound index tracking the combination of name and area. The second sheet has two indexes, but one is unique: it isn’t possible to add two items to the enemies sheet with the same name.
For sheets with unique indexes, you may specify a _violations key to indicate how the db layer handle cases where the data is duplicate (unique index is violated). The options you may use are:
  • FAIL - the default. A hard error is thrown, cancelling the script.
  • IGNORE - The command that would add a record that violates uniqueness just fails silently.
  • REPLACE - The old record which matched the unique index is dropped, and the new one is added to replace it.
Returns a reference of an already existing database. This instance can be used to get references to the sheets (and from there, fields) that are defined within the database. You use these references to construct queries.
If a database has a sheet named enemies, you can obtain a reference to that sheet by doing:
local mydb = db:get_database("myDatabase")
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 was broken in Mudlet 2.1 due to the underlying Lua SQL binding used being out of date. When you want to add a new column, you have several options:

  • if you are just testing and getting setup, close Mudlet, and delete the Database_<sanitized database name>.db file in your Mudlet folder.
  • if you've already gotten a script and have a fair bit of data with it, or users are already using your script and telling them to delete files on an upgrade is unreasonable, you can use direct SQL to add in a new column. WARNING, this is an expert option, and requires knowledge of SQL to accomplish. You must backup your database file before you start coding this in.
  -- at first, update your db:create schema to have the new field.
  -- then, we'll tell the database to create it if it doesn't exist

  -- fetch the data we've got in our sample database
  local test = db:fetch(ndb.db.people)
  -- this requires at least one entry in the database to work
  if next(test) then
    local _,someperson = next(test)
    
    -- in this example, we want to add an order key. If there is no key, means it doesn't exist yet, so it should be added.
    if someperson.order == nil then
      -- do not do the things you see here elsewhere else. This is a big hack/workaround.
      local conn = db.__conn.namedb
      -- order should be a text field, so note that we specify it's type with TEXT and the default value at the end with ""
      local sql_add = [[ALTER TABLE people ADD COLUMN "order" TEXT NULL DEFAULT ""]]
      conn:execute(sql_add)
      conn:commit()
    end

    -- here is an another example, in one where we need to add a field that is a number
    if someperson.dragon == nil then
      local conn = db.__conn.namedb
      -- observe that we use the REAL type by default instead and a default of 0
      local sql_add = [[ALTER TABLE people ADD COLUMN "dragon" REAL NULL DEFAULT 0]]
      conn:execute(sql_add)
      conn:commit()
    end
  end

See also: Creating a Database

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 db:gt.
  • 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:fetch_sql

db:fetch_sql(sheet reference, sql string)
Allows to run db:fetch with hand crafted sql statements.
When you have a large number of objects in your database, you may want an alternative method of accessing them. In this case, you can first obtain a list of the _row_id for the objects that match your query with the following alias:
Example
local mydb = db:get_database("itemsdab")
local query = matches[2]
local t = {}
res = db:fetch(mydb.itemstats, db:query_by_example(mydb.itemstats, {objname = "%" .. query .. "%"}))
for k, v in pairs(res) do
  print(v._row_id)
  table.insert(t,v._row_id)
end
handoff = table.concat(t, "|")
display(handoff)
Then you can use the following code in a separate alias to query your database using the previously retrieved _row_id.
Example
local mydb = db:get_database("itemsdab")
local query = matches[2]
display(db:fetch_sql(mydb.itemstats, "select * from itemstats where _row_id ="..query))
--This alias is used to query a database by _row_id

db:gt

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

db:get_database

db:get_database(database_name)
Returns a reference of an already existing database. This instance can be used to get references to the sheets (and from there, fields) that are defined within the database. You use these references to construct queries. These references do not contain any actual data, they only point to parts of the database structure.
Example
local mydb = db:get_database("my database")
local enemies_ref = mydb.enemies
local name_ref = mydb.enemies.name

db:gte

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

db:in_

db:in_(field reference, table array)
Returns a database expression to test if the field in the sheet is one of the values in the table array.
First, note the trailing underscore carefully! It is required.
The following example illustrates the use of in_:
local mydb = db:get_database("my database")
local areas = {"Undervault", "Hell", "Purgatory"}

db:fetch(mydb.kills, db:in_(mydb.kills.area, areas))
This will obtain all of your kills which happened in the Undervault, Hell or Purgatory. Every db:in_ expression can be written as a db:OR, but that quite often gets very complex.

db:is_nil

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

db:is_not_nil

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

db:like

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

db:lt

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

db:lte

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

db:merge_unique

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

db:not_between

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

db:not_eq

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

db:not_in

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

db:not_like

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

db:OR

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

db:query_by_example

db:query_by_example(sheet reference, example table)
Returns a query for database content matching the given example, which can be used for db:delete, db:fetch and db:set. Different fields of the example are AND connected.
Field values should be strings and can contain the following values:
  • literal strings to search for
  • comparison terms prepended with <, >, >=, <=, !=, <> for number and date comparisons
  • ranges with :: between lower and upper bound
  • different single values combined by || as OR
  • strings containing % for a single and _ for multiple wildcard characters
Mudlet VersionAvailable in Mudlet3.0+
Example
mydb = db:create("mydb",
{
  sheet = {
  name = "", id = 0, city = "",
  _index = { "name" },
  _unique = { "id" },
  _violations = "FAIL"
  }
})
test_data = {
  {name="Ixokai", city="Magnagora", id=1},
  {name="Vadi", city="New Celest", id=2},
  {name="Heiko", city="Hallifax", id=3},
  {name="Keneanung", city="Hashan", id=4},
  {name="Carmain", city="Mhaldor", id=5},
  {name="Ixokai", city="Hallifax", id=6},
}
db:add(mydb.sheet, unpack(test_data))
res = db:fetch(mydb.sheet, db:query_by_example(mydb.sheet, { name = "Ixokai"}))
display(res)
--[[
Prints
{
  {
    id = 1,
    name = "Ixokai",
    city = "Magnagora"
  },
  {
    id = 6,
    name = "Ixokai",
    city = "Hallifax"
  }
}
--]]
mydb = db:create("mydb",
  {
    sheet = {
    name = "", id = 0, city = "",
    _index = { "name" },
    _unique = { "id" },
    _violations = "FAIL"
    }
  })
test_data = {
  {name="Ixokai", city="Magnagora", id=1},
  {name="Vadi", city="New Celest", id=2},
  {name="Heiko", city="Hallifax", id=3},
  {name="Keneanung", city="Hashan", id=4},
  {name="Carmain", city="Mhaldor", id=5},
  {name="Ixokai", city="Hallifax", id=6},
}
db:add(mydb.sheet, unpack(test_data))
res = db:fetch(mydb.sheet, db:query_by_example(mydb.sheet, { name = "Ixokai", id = "1"}))
display(res)
--[[
  Prints
  {
    id = 1,
    name = "Ixokai",
    city = "Magnagora"
  }
--]]

db:Timestamp

db:Timestamp(time)
Returns a table that will be converted to an appropriate time. If the time argument is a table, it will be converted to the current OS time; if it is a number, it will be intrepreted as a Unix epoch time; if it is nil, it will be converted to a SQL NULL; it can also have the value of "CURRENT_TIMESTAMP", which will be converted to the corresponding SQL keyword.

db:Null

db:Null()
Returns a table that will be interpreted as the NULL SQL keyword.

db:safe_name

db:safe_name(string)
Strips all non-alphanumeric characters from the input string.Mainly used to sanitize database names.

db:set

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

db:update

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

db:_sql_convert

db:_sql_convert(value)
Converts a data value in Lua to its SQL equivalent; notably it will also escape single-quotes to prevent inadvertent SQL injection. In addition, it will convert Lua tables with a _timestamp key to the appropriate time (possibly CURRENT_TIMESTAMP) and Lua tables with a _isNull key to the NULL SQL keyword.

db:_sql_values

db:_sql_values(values)
This quotes values to be passed into an INSERT or UPDATE operation in a SQL list. Meaning, it turns {x="this", y="that", z=1} into ('this', 'that', 1). It is intelligent with data-types; strings are automatically quoted (with internal single quotes escaped), nil turned into NULL, timestamps converted to integers, and such.

Transaction Functions

These functions facilitate use of transactions with a database. This can safely be ignored in most cases, but can provide useful functionality in specific circumstances. Transactions allow batching sets of changes to be accepted or rejected at a later point. Bear in mind that transactions affect an entire database.

db:_begin

db:_begin()
This function halts all automatic disk writes for the database. This can be especially helpful when running large or frequent (multiple times a second) database edits through multiple function calls to prevent Mudlet freezing or jittering. Calling this on a database already in a transaction will have no effect, but will not produce an error.
local mydb = db:get_database("my_database")
mydb:_begin()
-- do other things as needed

db:_commit

db:_commit()
This function forces the database to save all changes to disk, beginning a new transaction in the process.
local mydb = db:get_database("my_database")
mydb:_begin()
-- do other things as needed
mydb:_commit()

db:_end

db:_end()
This function re-enables automatic disk writes for the database. It will not commit changes to disk on its own, nor will it end the current transaction. Using db:_commit() or any database function that writes changes after this will save the transaction to disk. Using db:_begin again before this happens will continue the previous transaction without writing anything to disk.
local mydb = db:get_database("my_database")
mydb:_end()

db:_rollback

db:_rollback()
This function will discard all changes that have occurred during the current transaction and begin a new one. Use of this function will not toggle the auto-write state of the database.
local mydb = db:get_database("my_database")
mydb:_begin()
-- do other things as needed
mydb:_rollback()