Manual:Lua Functions

From Mudlet
Revision as of 02:05, 11 December 2011 by Vadi (talk | contribs) (Added sendAll)
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

Scripting Object Functions

Mapper Functions

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

send

send( command, echo the value = true/false )
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.
If you want your command to be checked if it’s an alias, use expandAlias() instead. example:

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

echo

echo( windowName, text )
This function appends text at the end of the current line. The current cursor position is ignored. Use moveCursor() and insertText() if you want to print at a different cursor position.
If the first argument is omitted the main console is used, otherwise the mini console windowName. === Example 1:

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

UI Functions

echoLink

echoLink([windowName], text, command, hint, [bool use_current_format or defaultLinkFormat])
Echos a piece of text as a clickable link, at the end of the current selected line - similar to echo.
Parameters
  • text:
text to display in the echo. Same as a normal echo().
  • command:
lua code to do when the link is clicked.
  • hint:
text for the tooltip to be displayed when the mouse is over the link.
  • window:
if true, then the link will use the current selection style (colors, underline, etc). If missing or false, it will use the default link style - blue on black underlined text.

insertLink

insertLink([windowName], text, command, hint, [bool use_current_format or defaultLinkFormat])
Inserts a piece of text as a clickable link at the current cursor position - similar to insertText.
Parameters
  • text:
text to display in the echo. Same as a normal echo().
  • command:
lua code to do when the link is clicked.
  • hint:
text for the tooltip to be displayed when the mouse is over the link.
  • window:
if true, then the link will use the current selection style (colors, underline, etc). If missing or false, it will use the default link style - blue on black underlined text.

setlink

setlink(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
  • command:
command to do when the text is clicked
  • tooltip:
tooltip to show when the mouse is over the text - explaining what would clicking do
Example

<lua> -- you can clickify a lot of things to save yourself some time - for example, you can change -- the line where you receive a message to be clickable to read it! -- prel regex trigger: -- ^You just received message #(\w+) from \w+\.$ -- script: selectString(matches[2], 1) setUnderline(true) setLink(send("msg read ..matches[2].."), "Read #"..matches[2]) resetFormat() </lua>

appendBuffer

appendBuffer(name)
Pastes the previously copied rich text (including text formats like color etc.) into user window name.
See also: paste
Parameters
  • name:
The name of the user window to paste into. Passed as a string.
Examples

<lua> --selects and copies an entire line to user window named "Chat" selectCurrentLine() copy() appendBuffer("Chat") </lua>

fg

fg(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
  • colorName:
The name of the color to set the foreground to - list of possible names: Color Table
Examples

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

selectCurrentLine

selectCurrentLine()
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 that this selects the whole line, including the linebreak - so it has a subtle difference from the slightly slower selectString(line, 1) selection method.
See Also: selectString, getCurrentLine
Examples

<lua> -- color the whole line green! selectCurrentLine() fg("green") deselect() resetFormat() </lua>

bg

bg(colorName)
Changes the background color of the text. Useful for highlighting text.
See Also: fg, setBgColor
Parameters
  • colorName:
The name of the color to set the background to. Color Table
Example

<lua> --This would change the background color of the text on the current line to magenta selectCurrentLine() bg("magenta") </lua>

cecho

cecho(window, text)
Echoes text that can be easily formatted with colour tags.
See Also: decho, hecho
Parameters
  • window:
Optional - the window name to echo to - can either be none or "main" for the main window, or the miniconsoles name.
  • text:
The text to display, with color names inside angle brackets <>, ie <red>. If you'd like to use a background color, put it after a double colon : - <:red>. You can use the <reset> tag to reset to the default color. You can select any from this list: Color Table
Example

<lua> 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("myinfo", "<green>All of this text is green in the myinfo miniconsole.") </lua>

hecho

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


Example

<lua> hecho("|ca00040black!") </lua>

decho

decho(window, text)
Echoes text that can be easily formatted with colour tags in the hexadecimal format.
See Also: hecho, cecho
Parameters
  • window:
Optional - the window name to echo to - can either be none or "main" for the main window, or the miniconsoles name.
  • text:
Color changes can be made using the format <FR,FG,FB:BR,BG,BB> where each field is a number from 0 to 255. The background portion can be omitted using <FR,FG,FB> or the foreground portion can be omitted using <:BR,BG,BB>. You can also reset the color to default withh the <r> tag.


Example

<lua> decho("Hi, this is <255,0,0>red text<r> and this is <0,0,255>blue text<r>." </lua>

getCurrentLine

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

calcFontSize

calcFontSize(fontSize)
Used to calculate the number of pixels wide and high a character would be on a mini console at fontSize.
Returns two numbers, width/height
See Also: setMiniConsoleFontSize, getMainWindowSize
Parameters
  • fontSize:
The font size you are wanting to calculate pixel sizes for. Passed as an integer number.
Example

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

clearUserWindow

clearUserWindow(name)
Clears the window or miniconsole with the name given as argument.
Parameters
  • name:
The name of the user window to clear. Passed as a string.

Examples <lua> --This would clear a label, user window, or miniconsole with the name "Chat" clearUserWindow("Chat") </lua>

clearWindow

clearWindow(name)
Clears the window or miniconsole with the name given as argument. If you don't give it a name, it will clear the main window (since 2.0-test3+)
See also: clearUserWindow
Parameters
  • name:
The name of the user window to clear. Passed as a string.

Examples <lua> --This would clear a label, user window, or miniconsole with the name "Chat" clearWindow("Chat")

-- or this can clear your whole main window - needs 2.0-test3+ clearWindow() </lua>

createBuffer

createBuffer(name)
Creates a named buffer for formatted text, much like a miniconsole, but the buffer cannot be shown on the screen. Intended for temporary use in the formatting of text.
Parameters
  • name:
The name of the buffer to create.

Examples <lua> --This creates a named buffer called "scratchpad" createBuffer("scratchpad") </lua>

createConsole

createConsole(consoleName, fontSize, charsPerLine, numberOfLines, Xpos, Ypos)
Makes a new miniconsole. The background will be black, and the text color white.
Parameters
  • consoleName:
The name of your new miniconsole. Passed as a string.
  • fontSize:
The font size to use for the miniconsole. Passed as an integer number.
  • charsPerLine:
How many characters wide to make the miniconsole. Passed as an integer number.
  • numberOfLines:
How many lines high to make the miniconsole. Passed as an integer number.
  • Xpos:
X position of miniconsole. Measured in pixels, with 0 being the very left. Passed as an integer number.
  • Ypos:
Y position of miniconsole. Measured in pixels, with 0 being the very top. Passed as an integer number.

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

createGauge

createGauge(name, width, Xpos, Ypos, gaugeText, r, g, b)
createGauge(name, width, Xpos, Ypos, gaugeText, colorName)
Creates a gauge that you can use to express completion with. For example, you can use this as your healthbar or xpbar.
See also: moveGauge, setGauge, setGaugeText
Parameters
  • name:
The name of the gauge. Must be unique, you can not have two or more gauges with the same name. Passed as a string.
  • width:
The width of the gauge, in pixels. Passed as an integer number.
  • height:
The height of the gauge, in pixels. Passed as an integer number.
  • Xpos:
X position of gauge. Measured in pixels, with 0 being the very left. Passed as an integer number.
  • Ypos:
Y position of gauge. Measured in pixels, with 0 being the very top. Passed as an integer number.
  • gaugeText:
Text to display on the gauge. Passed as a string, unless you do not wish to have any text, in which case you pass nil
  • r:
The red component of the gauge color. Passed as an integer number from 0 to 255
  • g:
The green component of the gauge color. Passed as an integer number from 0 to 255
  • b:
The blue component of the gauge color. Passed as an integer number from 0 to 255
  • colorName:
the name of color for the gauge. Passed as a string.

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

createLabel

createLabel(name, Xpos, Ypos, width, height, fillBackground)
Creates a highly manipulable overlay which can take some css and html code for text formatting. Labels are clickable, and as such can be used as a sort of button. Labels are meant for small variable or prompt displays, messages, images, and the like. You should not use them for larger text displays or things which will be updated rapidly and in high volume, as they are much slower than miniconsoles.
Returns true or false.
See also: hideWindow, showWindow, resizeWindow, setLabelClickCallback, setTextFormat, setTextFormat, setMiniConsoleFontSize, setBackgroundColor, getMainWindowSize, calcFontSize
Parameters
  • name:
The name of the label. Must be unique, you can not have two or more labels with the same name. Passed as a string.
  • Xpos:
X position of the label. Measured in pixels, with 0 being the very left. Passed as an integer number.
  • Ypos:
Y position of the label. Measured in pixels, with 0 being the very top. Passed as an integer number.
  • width:
The width of the label, in pixels. Passed as an integer number.
  • height:
The height of the label, in pixels. Passed as an integer number.
  • fillBackground:
Whether or not to display the background. Passed as either 1 or 0. 1 will display the background color, 0 will not.

Examples <lua> --This example creates a transparent overlay message box to show a big warning message "You are under attack!" in the middle --of the screen. Because the background color has a transparency level of 150 (0-255, with 0 being completely transparent --and 255 non-transparent) the background text can still be read through. The message box will disappear after 2.3 seconds. local width, height = getMainWindowSize(); createLabel("messageBox",(width/2)-300,(height/2)-100,250,150,1); resizeWindow("messageBox",500,70); moveWindow("messageBox", (width/2)-300,(height/2)-100 ); setBackgroundColor("messageBox", 150,100,100,200);

echo("messageBox", [[

You are under attack!

]] );

showWindow("messageBox"); tempTimer(2.3, hideWindow("messageBox") ) -- close the warning message box after 2.3 seconds </lua>

createMiniConsole

createMiniConsole(name, posX, posY, 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.
Returns true or false.
See also: createLabel, hideWindow, showWindow, resizeWindow, setTextFormat, moveWindow, setMiniConsoleFontSize, handleWindowResizeEvent, setBorderTop, setWindowWrap, getMainWindowSize, calcFontSize
Parameters
  • name:
The name of the miniconsole. Must be unique, you can not have two or more miniconsoles with the same name. Passed as a string.
  • Xpos:
X position of the miniconsole. Measured in pixels, with 0 being the very left. Passed as an integer number.
  • Ypos:
Y position of the miniconsole. Measured in pixels, with 0 being the very top. Passed as an integer number.
  • width:
The width of the miniconsole, in pixels. Passed as an integer number.
  • height:
The height of the miniconsole, in pixels. Passed as an integer number.

Examples <lua> --This script would create a mini text console called "sys" and write with yellow foreground color and blue background color --"Hello World".


-- set up the small system message window in the top right corner -- determine the size of your screen WindowWidth = 0; WindowHeight = 0; WindowWidth, WindowHeight = getMainWindowSize();

createMiniConsole("sys",WindowWidth-650,0,650,300) setBackgroundColor("sys",85,55,0,255) setMiniConsoleFontSize("sys", 8) -- wrap lines in window "sys" at 40 characters per line setWindowWrap("sys", 40) -- set default font colors and font style for window "sys" setTextFormat("sys",0,35,255,50,50,50,0,0,0)

echo("sys","Hello world!") </lua>

setLabelClickCallback

setLabelClickCallback(labelName, luaFunctionName, optional any amount of arguments)
Specifies a Lua function to be called if the user clicks on the label/image. This function can pass any number of string or integer number values as additional parameters. These parameters are then used in the callback - thus you can associate data with the label/button.
Parameters
  • labelName:
The name of the label to attach a callback function to.
  • luaFunctionName:
The Lua function name to call, as a string - it must be registered as a global function, and not inside any namespaces (tables).
  • optional any amount of arguments:
Y position of the miniconsole. Measured in pixels, with 0 being the very top. Passed as an integer number.

Examples <lua> function onClickGoNorth()

 echo("the north button was clicked!")

end

setLabelClickCallback( "compassNorthImage", "onClickGoNorth" ) </lua>

setBackgroundColor

setBackgroundColor(labelName, red, green, blue, transparency)
Sets rgb color values and the transparency for the given window. Colors are from 0 to 255 (0 being black), and transparency is from - to 255 (0 being completely transparent).
Note that transparency only works on labels, not miniConsoles for efficiency reasons.
Parameters
  • labelName:
The name of the label to change it's background color.
  • red:
Amount of red to use, from 255 (full) to 0 (none).
  • green:
Amount of green to use, from 255 (full) to 0 (none).
  • blue:
Amount of red to use, from 255 (full) to 0 (none).
  • transparency:
Amount of transparency to use, from 255 (fully opaque) to 0 (fully transparent).

Examples <lua> -- make a red label that's somewhat transparent setBackgroundColor("some label",255,0,0,200) </lua>

setBackgroundImage

setBackgroundImage(labelName, imageLocation)
Loads an image file (png) as a background image for a label. This can be used to display clickable buttons in combination with setLabelClickCallback and such.
Note you can only do this for labels, not miniconsoles.
Note you can also load images via setLabelStyleSheet.
Parameters
  • labelName:
The name of the label to change it's background color.
  • imageLocation:
The full path to the image location. It's best to use [[ ]] instead of "" for it - because for Windows paths, backslashes need to be escaped.

Examples <lua> -- give the top border a nice look setBackgroundImage("top bar", /home/vadi/Games/Mudlet/games/top_bar.png) </lua>

setPopup

setPopup(name, {lua code}, {hints})
Turns the selected text into a left-clickable link, and a right-click menu for more options. The selected text, upon being left-clicked, will do the first command in the list. Upon being right-clicked, it'll display a menu with all possible commands. The menu will be populated with hints, one for each line.
Parameters
  • name:
the name of the console to operate on. If not using this in a miniConsole, use "main" as the name.
  • {lua code}:
a table of lua code strings to do. ie, <lua>{send("hello"), echo("hi!"}</lua>.
  • {hints}:
a table of strings which will be shown on the popup and right-click menu. ie, <lua>{"send the hi command", "echo hi to yourself"}</lua>.
Example

<lua> -- 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 left-clicking -- will show some commands you can do.

selectString("Hello", 1) setPopup("main", {send("bye"), echo("hi!")}, {"left-click or right-click and do first item to send bye", "click to echo hi"}) </lua>

echoPopup

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

<lua> -- Create some text as a clickable with a popup menu: echoPopup("activities to do", {send "sleep", send "sit", send "stand"}, {"sleep", "sit", "stand"}) </lua>

insertPopup

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

<lua> -- Create some text as a clickable with a popup menu: insertPopup("activities to do", {send "sleep", send "sit", send "stand"}, {"sleep", "sit", "stand"}) </lua>

deleteLine

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

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

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

<lua>selectString(line,1) replace("")</lua>

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

<lua> -- re-wrap the last line in the main window wrapLine("main", getLineCount()) </lua>

deselect

deselect(name)
This is used to clear the current selection (to no longer have anything selected). Should be used after changing the formatting of text, to keep from accidentally changing the text again later with another formatting call.
Parameters
  • name:
The name of the buffer/miniConsole to stop having anything selected in. This is an optional argument, if name is not provided the main window will have its selection cleared. Passed as a string.
Example

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

isAnsiFgColor

isAnsiFgColor(ansiFgColorCode)
This function tests if the first character of the current selection has the foreground color specified by ansiFgColorCode.
Parameters
  • ansiFgColorCode:
A color code to test for, possible codes are:

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

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

isAnsiBgColor

isAnsiBgColor(ansiBgColorCode)
This function tests if the first character of the current selection has the backgroundground color specified by ansiBgColorCode.
Parameters
  • ansiBgColorCode:
A color code to test for, possible codes are:

<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> selectString( matches[1], 1 ) if isAnsiBgColor( 5 ) then

   bg("red");
   resetFormat();
   echo("yes, the background of the text is light green")

else

   echo( "no sorry, some other backgroundground color" )

end </lua>

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

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

<lua> local r,g,b; selectString("troll",1) r,g,b = getFgColor() if r == 255 and g == 0 and b == 0 then

   echo("HELP! troll is written in red letters, the monster is aggressive!\n");

end </lua>

getBgColor

getBgColor(windowName)
This function returns the rgb values of the background color of the first character of the current selection on mini console (window) windowName. If windowName is omitted Mudlet will use the main screen.
Parameters
  • windowName:
A window to operate on - either a miniconsole or the main window.
Examples

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

setBorderColor

setBorderColor(r,g,b)
Sets the color of the main windows border that you can create either with setBorderTop(), setBorderBottom(), setBorderLeft(), setBorderRight(), or via the main window settings.
See Also: setBorderTop, setBorderBottom, setBorderLeft, setBorderRight
Parameters
  • r:
Amount of red to use, from 0 to 255.
  • g:
Amount of green to use, from 0 to 255.
  • b:
Amount of blue to use, from 0 to 255.
Examples

<lua> -- set the border to be completely blue setBorderColor(0, 0, 255)

-- or red, using a name setBorderColor( unpack(color_table.red) ) </lua>

setBorderRight

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

<lua> setBorderRight(100) </lua>

setBorderLeft

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

<lua> setBorderLeft(100) </lua>

setBorderBottom

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

<lua> setBorderLeft(100) </lua>

setBorderTop

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

<lua> setBorderTop(100) </lua>

getMainConsoleWidth

getMainConsoleWidth()
Returns a single number; the width of the main console (MuD output) in pixels.
No Parameters
Example

<lua> -- Save width of the main console to a variable for future use. consoleWidth = getMainConsoleWidth() </lua>

hasFocus

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

<lua> if attacked and not hasFocus() then

 runaway()

else

 fight()

end </lua>

getMainWindowSize

getMainWindowSize()
Returns two numbers, the width and height in pixels.
No Parameters
Example

<lua> --this will get the size of your main mudlet window and save them --into the variables mainHeight and mainWidth mainWidth, mainHeight = getMainWindowSize() </lua>

showToolBar

showToolBar(name)
Makes a toolbar (a button group) appear on the screen.
Parameters
  • name:
name of the button group to display
Example

<lua> showToolBar("my offensive buttons") </lua>

hideToolBar

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

<lua> hideToolBar("my offensive buttons") </lua>

resetFormat

resetFormat()
Resets the colour/bold/italics formatting. Always use this function when done adjusting formatting, so make sure what you've set doesn't 'bleed' onto other triggers/aliases.
Example

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

setLabelStyleSheet

setLabelStyleSheet(label, markup)
Applies Qt style formatting to a label via a special markup language.
Parameters
  • label:
The name of the label to be formatted (passed when calling createLabel).
  • markup:
The string instructions, as specified by the Qt Style Sheet reference.
References
http://doc.qt.nokia.com/4.7/stylesheet-reference.html#list-of-properties
Example

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

handleWindowResizeEvent

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

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

Example

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

Table Functions

table.complement

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

<lua></lua>

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

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

table.contains

table.contains (t, value)
Determines if a table contains a value as a key or as a value (recursive).
Returns true or false
Parameters
  • t:
The table in which you are checking for the presence of the value.
  • value:
The value you are checking for within the table.
Example

<lua>local test_table = { "value1", "value2", "value3", "value4" } if table.contains(test_table, "value1") then

  echo("Got value 1!")

else

  echo("Don't have it. Sorry!")

end </lua> This example would always echo the first one, unless you remove value1 from the table.

table.foreachi

table.foreach

table.getn

table.intersection

table.insert

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

Inserting a function into a table is not good coding practice, and will not turn out how you think it would.

table.index_of

table.is_empty

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

table.load

table.load(location, table)
Load a table from an external file into mudlet.
See also: table.save
Parameters
  • location:
Where you are loading the table from. Can be anywhere on your computer.
  • table:
The table that you are loading.
Example:

<lua> -- This will load the table mytable from the lua file mytable present in your Mudlet Home Directory. table.load(getMudletHomeDir().."/mytable.lua", mytable) -- You can load a table from anywhere on your computer, but it's preferable to have them consolidated somewhere connected to Mudlet. </lua>

table.maxn

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

table.n_union

table.n_complement

table.n_intersection

table.pickle

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

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

Note

To remove a value from a key-value table, it's best to simply change the value to nil. <lua> 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 </lua>

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:

<lua> -- Saves the table mytable to the lua file mytable in your Mudlet Home Directory table.save(getMudletHomeDir().."/mytable.lua", mytable) </lua>

table.sort

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

table.size

table.size (t)
Gets the actual size of non-index based tables.
Returns a number.
Parameters
  • t:
The table you are checking the size of.
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.

Example

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

table.setn

table.unpickle

table.update

table.union

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

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

[[ ]] 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>

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>

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>

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. itemtype can be timer, trigger, or alias.

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>


setConsoleBufferSize

setConsoleBufferSize( consoleName, linesLimit, sizeOfBatchDeletion )

Set the maximum number of lines can a buffer (main window or a miniconsole) can hold. linesLimit sets the amount of lines the buffer should have - 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.

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


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>


isActive

isActive(name, type)

You can use this function to check if something, or somethings, are active. Type can be either "alias", "trigger", or "timer", and name is the name of the said item you’d like to check.

Example

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

getButtonState

getButtonState()

This function can only be used inside a toggle button script - it'll return 2 if button is checked, and 1 if it's not.

Example

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

   hideExits()

else

   showExits()

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>

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>

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>