Difference between revisions of "Manual:Event Engine"

From Mudlet
Jump to navigation Jump to search
 
(136 intermediate revisions by 18 users not shown)
Line 1: Line 1:
 
{{TOC right}}
 
{{TOC right}}
 +
{{#description2:Manual on events, which events exist, how to raise events, how to handle them.}}
 
=Event System=
 
=Event System=
  
 
Events in Mudlet allow a paradigm of system-building that is easy to maintain (because if you’d like to restructure something, you’d have to do less work), enables interoperability (making a collection of scripts that work with each other is easier) and enables an event-based way of programming.
 
Events in Mudlet allow a paradigm of system-building that is easy to maintain (because if you’d like to restructure something, you’d have to do less work), enables interoperability (making a collection of scripts that work with each other is easier) and enables an event-based way of programming.
  
The essentials of it are as such: you use Scripts to define which events should a function to listen to, and when the event is raised, the said function(s) will be called. Events can also have function parameters with them, which’ll be passed onto the receiving functions.
+
The essentials of it are as such: you use Scripts to define which events a function should listen to, and when the event is raised, the said function(s) will be called. Events can also have function parameters with them, which’ll be passed onto the receiving functions.
  
 
== Registering an event handler via UI ==
 
== Registering an event handler via UI ==
Registering an event handler means that you’ll be telling Mudlet what function should it call for you when an event is raised, so it’s a two step process - you need to tell it both what function you’d like to be called, and on what event should it be called.
+
Registering an event handler means that you’ll be telling Mudlet what function it should call for you when an event is raised, so it’s a two step process - you need to tell it both what function you’d like to have called, and on what event it should be called.
  
To tell it what function should be called, create a new script, and give the script the name of the function you’d like to be called. This is the only time where an items name matters in Mudlet. You can define the function right inside the script as well, if you’d like.
+
To tell it what function should be called, create a new script, and '''give the script the name of the function you’d like to be called'''. This is the only time where an items name matters in Mudlet. You can define the function right inside the script as well, if you’d like.
  
Next, we tell it what event or events should this function be called on - you can add multiple ones. To do that, enter the events name in the Add User Defined Event Handler: field, press enter, and it’ll go into the list - and that is all.
+
Next, we tell it what event or events this function should be called on - you can add multiple entries. To do that, enter the events name in the Add User Defined Event Handler: field, press enter, and it’ll go into the list - and that is all.
 +
 
 +
[[File:Gui-event-handler.png|600px|center]]
  
 
== Registering an event from a script ==
 
== Registering an event from a script ==
You can also register your event with the ''[[Manual:Miscellaneous_Functions#registerAnonymousEventHandler|registerAnonymousEventHandler(event name, function name)]]'' function inside your scripts:
+
You can also register your event with the ''[[Manual:Miscellaneous_Functions#registerAnonymousEventHandler|registerAnonymousEventHandler(event name, function reference, [one shot])]]'' function inside your scripts:
  
<lua>
+
<syntaxhighlight lang="lua">
 
-- example taken from the God Wars 2 (http://godwars2.org) Mudlet UI - forces the window to keep to a certain size
 
-- example taken from the God Wars 2 (http://godwars2.org) Mudlet UI - forces the window to keep to a certain size
 
function keepStaticSize()
 
function keepStaticSize()
Line 22: Line 25:
 
end -- keepStaticSize
 
end -- keepStaticSize
  
registerAnonymousEventHandler("sysWindowResizeEvent", "keepStaticSize")
+
registerAnonymousEventHandler("sysWindowResizeEvent", keepStaticSize, false)
</lua>
+
</syntaxhighlight>
  
{{note}} Mudlet also uses the event system in-game protocols (like ATCP, GMCP and others).
+
{{Note}}: [https://wiki.mudlet.org/w/Manual:Lua_Functions#registerNamedEventHandler registerNamedEventHandler] can also be used. Doing so causes Mudlet to handle saving of the IDs for you.
  
{{note}} Event handler functions can now also be in namespaces (tables).
+
{{Note}} Mudlet also uses the event system in-game protocols (like GMCP, MSDP and others).
  
== Raising an event==  
+
== Raising a custom event==  
To raise an event, you’d use the [[Manual:Lua_Functions#raiseEvent|raiseEvent()]] function:
+
To raise an event, you'd use the [[Manual:Lua_Functions#raiseEvent|raiseEvent()]] function:
  
<lua>raiseEvent(name, [arguments...])</lua>
+
<syntaxhighlight lang="lua">raiseEvent(name, [arguments...])</syntaxhighlight>
  
 
It takes an event name as the first argument, and then any amount of arguments after it which will be passed onto the receiving functions.
 
It takes an event name as the first argument, and then any amount of arguments after it which will be passed onto the receiving functions.
  
;Mini-tutorial
+
== Example of registering and raising an event ==
As an example, our prompt trigger could raise an ''onPrompt'' event if you want to attach 2 functions to it. In your prompt trigger, all you’d need to do is ''raiseEvent("onPrompt")''. Now we go about creating functions that attach to the event - lets say the first one is ''check_health_stuff()'' and the other is ''check_salve_stuff()''. We would like these to be executed when the event is raised. So create a script and give it a name of ''check_health_stuff''. In the '''Add user defined event handler''', type ''onPrompt'', and press enter to add it to the list. In the script box, create:
+
Add a script to each profile you need the event.
  
<lua>
+
<syntaxhighlight lang="lua">
function check_health_stuff()
+
 
   echo("I work!\n")
+
-- This is the function that will be called when the event is raised.
 +
-- "event" is set to the event name.
 +
-- "arg" is the argument(s) provided with raiseEvent/raiseGlobalEvent.
 +
-- "profile" - Is the profile name from where the raiseGlobalEvent was triggered from
 +
--            It is 'nil' if raiseEvent() was used.
 +
function onMyEvent(event, arg, profile)
 +
   echo("Event: " .. event .. "\n")
 +
  echo("Arg  : " .. arg .. "\n")
 +
  -- If the event is not raised with raiseGlobalEvent() profile will be 'nil'
 +
  echo("Profile: " .. (profile or "Local") .. "\n")
 
end
 
end
</lua>
 
  
When the onPrompt event comes along, that script catches it, and runs ''check_health_stuff()'' for you.
+
-- Register the event handler.
 +
registerAnonymousEventHandler("my_event", onMyEvent)
 +
</syntaxhighlight>
  
[[Link title]]
+
To raise the event you can call:
 +
<syntaxhighlight lang="lua">
 +
-- Trigger only in the current profile:
 +
raiseEvent("my_event", "Hello world!")
 +
 
 +
-- Trigger the event in all OTHER profiles:
 +
raiseGlobalEvent("my_event", "Hello World!")
 +
</syntaxhighlight>
 +
 
 +
To review, count and extract from an unknown number of arguments received by an event:
 +
 
 +
<syntaxhighlight lang="lua">
 +
function eventArgs(...)
 +
  local args = {...}
 +
  local amount = #args
 +
  local first = args[1]
 +
  echo("Number of arguments: " .. amount)
 +
  echo("\nTable of all arguments: ")
 +
  display(args)
 +
  echo("First argument: " .. first)
 +
  echo("\n\n")
 +
end
 +
</syntaxhighlight>
 +
 
 +
== Gamepad functionality ==
 +
{{note}} will be removed in 4.18 as this is blocking Mudlet updates and is not used by players.
 +
 
 +
Gamepad functions are not fully supported with all operating systems and hardware.  Windows supports XInput devices like Xbox 360 and Xbox One controllers.  DirectInput controllers like a PlayStation 4 controller can be translated to XInput with third party software.  Mudlet on Linux can support gamepads but only if you compile it yourself.  The automated builds are made using the oldest supported version of Ubuntu, and the [https://doc.qt.io/qt-5/qtgamepad-index.html Qt5 gamepad module] was [https://packages.ubuntu.com/search?keywords=libqt5gamepad5-dev not available on Ubuntu 18.04 LTS].
  
 
==Mudlet-raised events==
 
==Mudlet-raised events==
 
Mudlet itself also creates events for your scripts to hook on. The following events are generated currently:
 
Mudlet itself also creates events for your scripts to hook on. The following events are generated currently:
 +
 +
===AdjustableContainerReposition===
 +
Raised while a [[Manual:Geyser#Adjustable.Container|adjustable container]] is re-positioned. 
 +
 +
<syntaxhighlight lang="lua">
 +
function repositioningContainer(eventName, containerName, width, height, x, y, mouseAction)
 +
  print(f"{containerName}: {x}x, {y}y, {width}x{height}, using mouse? {mouseAction}")
 +
end
 +
 +
registerAnonymousEventHandler("AdjustableContainerReposition", repositioningContainer)
 +
</syntaxhighlight>
 +
 +
===AdjustableContainerRepositionFinish===
 +
Raised when an [[Manual:Geyser#Adjustable.Container|adjustable container]] done being re-positioned.
 +
 +
<syntaxhighlight lang="lua">
 +
function finishedRepositioning(eventName, containerName, width, height, x, y)
 +
  print(f"{containerName}: {x}x, {y}y, {width}x{height}")
 +
end
 +
 +
registerAnonymousEventHandler("AdjustableContainerRepositionFinish", finishedRepositioning)
 +
</syntaxhighlight>
 +
 +
===channel102Message===
 +
 +
Raised when a telnet sub-option 102 message is received (which comprises of two numbers passed in the event). This is of particular use with the [http://www.aardwolf.com Aardwolf MUD] who originated this protocol. See [http://forums.mudlet.org/viewtopic.php?f=6&t=1471 this] forum topic for more about the Mudlet Aardwolf GUI that makes use of this.
 +
 +
===mapModeChangeEvent===
 +
 +
Raised when the mapper is switching between "view-only" and "editing" mode of the [[Manual:Mapper#Visual_Map_Editor|Visual Map Editor]]. A value of "editing" or "viewing" will be given as argument to indicate which mode was entered.
  
 
===mapOpenEvent===
 
===mapOpenEvent===
Line 56: Line 126:
 
Raised when the mapper is opened - either the floating dock or the in-Mudlet widget.
 
Raised when the mapper is opened - either the floating dock or the in-Mudlet widget.
  
===sysWindowResizeEvent===
+
===sysAppStyleSheetChange===
 +
 
 +
Raised when [[Manual:UI_Functions#setAppStyleSheet|setAppStyleSheet]] is called and a new stylesheet applied to Mudlet.
 +
 
 +
<syntaxhighlight lang="lua">
 +
-- This will respond to a future (as yet unpublished) addition to the Mudlet code that will allow some
 +
-- of a default application style sheet to be supplied with Mudlet to compensate for some text colors
 +
-- that do not show up equally well in both light and dark desktop themes. That, perhaps, might finally
 +
-- allow different colored texts to be uses again for the trigger item types!
 +
function appStyleSheetChangeEvent( event, tag, source )
 +
  if source == "system" then
 +
    colorTable = colorTable or {}
 +
    if tag == "mudlet-dark-theme" then
 +
      colorTable.blue = {64, 64, 255}
 +
      colorTable.green = {0, 255, 0}
 +
    elseif tag == "mudlet-light-theme" then
 +
      colorTable.blue = {0, 0, 255}
 +
      colorTable.green = {64, 255, 64}
 +
    end
 +
  end
 +
end
 +
</syntaxhighlight>
 +
 
 +
{{MudletVersion|3.19}}
 +
 
 +
===sysBufferShrinkEvent===
 +
 
 +
Raised when the oldest lines are removed from the back of any console or buffer belonging to a profile because it has reached the limit (either the default or that set by [[Manual:Mudlet_Object_Functions#setConsoleBufferSize|setConsoleBufferSize]]). The two additional arguments within the event are: the name of the console or buffer and the number of lines removed from the beginning of the buffer. This information will be useful for any situation where a line number is being stored as it will need to be decremented by that number of lines in order to continue to refer to the same line (assuming that it is still present - indicated by the number remaining positive) after the oldest ones have been removed.
 +
 
 +
{{MudletVersion|4.17}}
 +
 
 +
===sysConnectionEvent===
 +
 
 +
Raised when the profile becomes connected to a MUD.
 +
 
 +
===sysCustomHttpDone===
 +
 
 +
Raised whenever a [[Manual:Networking_Functions#customHTTP|customHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters) and HTTP method.
 +
 
 +
See also [[#sysCustomHttpError|sysCustomHttpError]].
 +
 
 +
===sysCustomHttpError===
 +
 
 +
Raised whenever a [[Manual:Networking_Functions#customHTTP|customHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to and HTTP method.
 +
 
 +
See also [[#sysCustomHttpDone|sysCustomHttpDone]].
 +
 
 +
===sysDataSendRequest===
 +
 
 +
Raised right before a command from the send(), sendAll() functions or the command line is sent to the game - useful for keeping track of what your last command was, manipulating input or even denying the command to be sent if necessary with [[Manual:Miscellaneous_Functions#denyCurrentSend|denyCurrentSend()]].
  
Raised when the main window is resized, with the new height and width coordinates passed to the event. A common usecase for this event is to move/resize your UI elements according to the new dimensions.
+
sysDataSendRequest will send the event name and the command sent (in string form) to the functions registered to it. IE: commandSent in the example below will be "eat hambuger" if the user entered only that into command line and pressed enter, send("eat hamburger"), sendAll("eat humburger", "eat fish") or sendAll("eat fish", "eat humburger")
Example
 
  
This sample code will echo whenever a resize happened with the new dimensions:
+
Note: if you'll be making use of denyCurrentSend(), you ''really should'' notify the user that you denied their command - unexperienced ones might conclude that your script or Mudlet is buggy if they don't see visual feedback. Do not mis-use this and use it as [http://en.wikipedia.org/wiki/Keylogger keylogger] either.
  
<lua>
+
<syntaxhighlight lang="lua">
function resizeEvent( event, x, y )
+
-- cancels all "eat hambuger" commands
   echo("RESIZE EVENT: event="..event.." x="..x.." y="..y.."\n")
+
function cancelEatHamburger(eventName, commandSent)
 +
   if commandSent == "eat hamburger" then
 +
    denyCurrentSend() --cancels the command sent.
 +
    cecho("<red>Denied! You can't do "..commandSent.." right now.\n")
 +
  end --if commandSent == eat hamburger
 
end
 
end
</lua>
 
  
===sysWindowMousePressEvent===
+
registerAnonymousEventHandler("sysDataSendRequest", cancelEatHamburger)
 +
</syntaxhighlight>
  
Raised when a mouse button is pressed down anywhere on the main window (note that a click is composed of a mouse press and mouse release). The button number and the x,y coordinates of the click are reported.
+
If you wanted to control input you could set a bool after a trigger.
Example
+
This is useful if you want alias like control, do not know what text will be entered, but do know a trigger that WILL occur just before the user enters the command.
  
<lua>
+
<syntaxhighlight lang="lua">
function onClickHandler( event, button, x, y )
+
function controlInput(_, command)  
   echo("CLICK event:"..event.." button="..button.." x="..x.." y="..y.."\n")
+
   if changeCMDInput then
 +
    changeCMDInput = false --set this if check to false to it doesn't occur every input
 +
    --Also set the bool check BEFORE any send() functions within a sysDataSendRequest function
 +
    sendAll(command .. "some target", command .. "some other target", true) --Duplicate and unknown command
 +
    denyCurrentSend() --Deny the original command, not the commands sent with sendAll.
 +
  end
 
end
 
end
</lua>
+
registerAnonymousEventHandler("sysDataSendRequest", controlInput)
 +
</syntaxhighlight>
 +
 
 +
Take note that functions registered under sysDataSendRequest WILL trigger with ALL commands that are sent.
 +
 
 +
===sysDeleteHttpDone===
 +
 
 +
Raised whenever a [[Manual:Networking_Functions#deleteHTTP|deleteHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).
  
===sysWindowMouseReleaseEvent===
+
See also [[#sysDeleteHttpError|sysDeleteHttpError]].
 +
 
 +
===sysDeleteHttpError===
 +
 
 +
Raised whenever a [[Manual:Networking_Functions#deleteHTTP|deleteHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.
  
Raised when a mouse button is released after being pressed down anywhere on the main window (note that a click is composed of a mouse press and mouse release). See sysWindowMousePressEvent for example use.
+
See also [[#sysDeleteHttpDone|sysDeleteHttpDone]].
  
===sysLoadEvent===
+
===sysDisconnectionEvent===
  
Raised when Mudlet is loading the profile. Note that when it does so, it also compiles and runs all scripts - which could be a good idea to initialize everything at, but beware - scripts are also run when saved. Hence, hooking only on the sysLoadEvent would prevent multiple re-loads as you’re editing the script.
+
Raised when the profile becomes disconnected, either manually or by the game.
  
===sysExitEvent===
+
If you'd like to automatically reconnect when you get disconnected, make a new <code>Script</code> and add this inside:
  
Raised when Mudlet is shutting down the profile - a good event to hook onto for saving all of your data.
+
<syntaxhighlight lang="lua">
 +
registerAnonymousEventHandler("sysDisconnectionEvent", reconnect)
 +
</syntaxhighlight>
  
 
===sysDownloadDone===
 
===sysDownloadDone===
  
Raised when Mudlet is finished downloading a file successfully - the location of the downloaded file is passed as a second argument.
+
Raised when Mudlet is finished downloading a file successfully - the location of the downloaded file is passed as a second argument, the file size is passed as the third, and the HTTP response is passed as the fourth.
  
 
Example - put it into a new script and save it to run:
 
Example - put it into a new script and save it to run:
  
<lua>
+
<syntaxhighlight lang="lua">
 
-- create a function to parse the downloaded webpage and display a result
 
-- create a function to parse the downloaded webpage and display a result
 
function downloaded_file(_, filename)
 
function downloaded_file(_, filename)
Line 116: Line 256:
  
 
-- register our function to run on the event that something was downloaded
 
-- register our function to run on the event that something was downloaded
registerAnonymousEventHandler("sysDownloadDone", "downloaded_file")
+
registerAnonymousEventHandler("sysDownloadDone", downloaded_file)
  
 
-- download a list of fake users for a demo
 
-- download a list of fake users for a demo
 
downloadFile(getMudletHomeDir().."/achaea-who-count.html", "https://www.achaea.com/game/who")
 
downloadFile(getMudletHomeDir().."/achaea-who-count.html", "https://www.achaea.com/game/who")
</lua>
+
</syntaxhighlight>
  
 
You should see a result like this:
 
You should see a result like this:
  
[[File:DownloadFile_demo.png]]
+
[[File:DownloadFile_demo.png|frameless|800px]]
  
 
===sysDownloadError===
 
===sysDownloadError===
  
Raised when downloading a file failed - the second argument contains the error message. Starting with Mudlet 2.0-test5+, it specifies the original URL that was going to be downloaded.
+
Raised when downloading a file failed - the second argument contains the error message, the third the local filename that was to be used and the actual URL used (might not be the same as what was given if redirection took place).
 +
 
 +
;Example
 +
<syntaxhighlight lang="lua">
 +
--if a download fails notify the player.
 +
function downloadErrorEventHandler(event, errorFound, localFilename, usedUrl)
 +
    cecho("fuction downloadErrorEventHandler, "..errorFound)
 +
    debugc("fuction downloadErrorEventHandler, "..errorFound) --display to error screen in editor
 +
end --function downloadErrorEventHandler
 +
registerAnonymousEventHandler("sysDownloadError", downloadErrorEventHandler)
 +
</syntaxhighlight>
 +
 
 +
===sysDownloadFileProgress===
 +
 
 +
Raised while file is being downloaded to indicate progess of download.
 +
 
 +
The arguments passed areː: event name, url of download, bytes downloaded, total bytes (if available).
 +
 
 +
;Example
 +
<syntaxhighlight lang="lua">
 +
-- will show progress bar while download file and hide it after file download is complete
 +
local progressBar = Geyser.Gauge:new({
 +
  name="downloadProgressBar",
 +
  x="25%", y="10%",
 +
  width="50%", height="5%",
 +
})
 +
progressBar:setFontSize(13)
 +
progressBar:setAlignment("center")
 +
progressBar:hide()
 +
 
 +
 
 +
local fileUrl = "https://www.mudlet.org/download/Mudlet-4.10.1-linux-x64.AppImage.tar"
 +
local targetFile = getMudletHomeDir() .. "/Mudlet.tar"
 +
function handleProgress(_, url, bytesDownloaded, totalBytes)
 +
  if url ~= fileUrl then
 +
    return
 +
  end
 +
 
 +
  progressBar:show()
 +
 
 +
  if not totalBytes then
 +
    bytesDownloaded = 0
 +
    totalBytes = 1
 +
  end
 +
 
 +
  progressBar:setValue(bytesDownloaded, totalBytes, math.floor((bytesDownloaded / totalBytes) * 100) .. "%")
 +
end
 +
 
 +
registerAnonymousEventHandler("sysDownloadFileProgress", handleProgress)
 +
 
 +
function hideProgressBar()
 +
  tempTimer(3, function() progressBar:hide() end)
 +
end
 +
 
 +
registerAnonymousEventHandler("sysDownloadDone", hideProgressBar)
 +
registerAnonymousEventHandler("sysDownloadError", hideProgressBar)
 +
 
 +
downloadFile(targetFile, fileUrl)
 +
</syntaxhighlight>
 +
 
 +
{{MudletVersion|4.11}}
 +
 
 +
===sysDropEvent===
 +
 
 +
Raised when a file is dropped on the Mudlet main window or a userwindow.
 +
The arguments passed areː filepath, suffix, xpos, ypos, and consolename - "main" for the main window and otherwise of the userwindow/miniconsole name.
 +
 
 +
{{MudletVersion|4.8}}
 +
 
 +
<syntaxhighlight lang="lua">
 +
function onDragAndDrop(_, filepath, suffix, xpos, ypos, consolename)
 +
  print(string.format("Dropped new file into %s: %s (suffix: %s)", consolename, filepath, suffix))
 +
end
 +
registerAnonymousEventHandler("sysDropEvent", onDragAndDrop)
 +
</syntaxhighlight>
 +
 
 +
===sysDropUrlEvent===
 +
 
 +
Raised when a url is dropped on the Mudlet main window or a userwindow.
 +
As an url at the moment Mudlet understands
 +
The arguments passed areː url, schema, xpos, ypos, and consolename - "main" for the main window and otherwise of the userwindow/miniconsole name.
 +
 
 +
{{MudletVersion|4.11}}
 +
 
 +
<syntaxhighlight lang="lua">
 +
function onDragAndDropUrl(_, url, schema, xpos, ypos, consolename)
 +
  print(string.format("Dropped new url into %s: %s (suffix: %s)", consolename, filepath, suffix))
 +
  if schema == "http" or schema == "https" then
 +
    print("\nOh boy... this might be a link to some website")
 +
  end
 +
end
 +
registerAnonymousEventHandler("sysDropUrlEvent", onDragAndDropUrl)
 +
</syntaxhighlight>
 +
 
 +
===sysExitEvent===
 +
 
 +
Raised when Mudlet is shutting down the profile - a good event to hook onto for saving all of your data.
 +
 
 +
===sysGetHttpDone===
 +
 
 +
Raised whenever a [[Manual:Networking Functions#getHTTP|getHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).
 +
 
 +
This event is also raised when a post/put/delete request redirects to a ''GET''.
 +
 
 +
See also [[#sysGetHttpError|sysGetHttpError]].
 +
 
 +
{{MudletVersion|4.10}}
 +
 
 +
===sysGetHttpError===
 +
 
 +
Raised whenever a [[Manual:Networking_Functions#getHTTP|getHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.
 +
 
 +
See also [[#sysGetHttpDone|sysGetHttpDone]].
 +
 
 +
{{MudletVersion|4.10}}
 +
 
 +
===sysInstall===
 +
 
 +
Raised right after a module or package is installed by any means. This can be used to display post-installation information or setup things.
 +
 
 +
Event handlers receive the name of the installed package or module as additional argument.
 +
 
 +
{{note}}Installed modules will raise this event handler each time the synced profile is opened. [[#sysInstallModule|sysInstallModule]] and [[#sysInstallPackage|sysInstallPackage]] are not raised by opening profiles.
 +
 
 +
{{MudletVersion|3.1}}
 +
 
 +
<syntaxhighlight lang="lua">
 +
function myScriptInstalled(_, name)
 +
  -- stop if what got installed isn't my thing
 +
  if name ~= "my script name here" then return end
 +
 
 +
  print("Hey, thanks for installing my thing!")
 +
end
 +
registerAnonymousEventHandler("sysInstallPackage", myScriptInstalled)
 +
</syntaxhighlight>
 +
 
 +
===sysInstallModule===
 +
 
 +
Raised right after a module is installed through the module dialog. This can be used to display post-installation information or setup things.
 +
 
 +
See also [[#sysLuaInstallModule|sysLuaInstallModule]] for when a module is installed via Lua.
 +
 
 +
Event handlers receive the name of the installed module as well as the file name as additional arguments.
 +
 
 +
{{MudletVersion|3.1}}
 +
 
 +
===sysInstallPackage===
 +
 
 +
Raised right after a package is installed by any means. This can be used to display post-installation information or setup things.
 +
 
 +
Event handlers receive the name of the installed package as well as the file name as additional arguments.
 +
 
 +
{{MudletVersion|3.1}}
  
 
===sysIrcMessage===
 
===sysIrcMessage===
  
Raised when you see or receive an IRC message. The speakers name, channel and their message will follow as arguments.
+
Raised when the IRC client receives an IRC message. The sender's name, channel name, and their message are passed as arguments to this event. 
 +
 
 +
Starting with Mudlet 3.3, this event changes slightly to provide more information from IRC network messages. Data such as status codes, command responses, or error messages sent by the IRC Server may be formatted as plain text by the client and posted to lua via this event.
 +
 
 +
* sender: may be the nick name of an IRC user or the name of the IRC server host, as retrievable by  [[Manual:Networking_Functions#getIrcConnectedHost|getIrcConnectedHost()]] 
 +
* channel: may not always contain a channel name, but will be the name of the target/recipient of a message or action. In some networks the name may be that of a service (like ''"Auth"'' for example) 
  
<lua>
+
;Example
function onIrcMessage(_, person, channel, message)
+
<syntaxhighlight lang="lua">
   echo(string.format('(%s) %s says, "%s"\n', channel, person, message))
+
function onIrcMessage(_, sender, target, message)
 +
   echo(string.format('(%s) %s says, "%s"\n', target, sender, message))
 
end
 
end
</lua>
 
  
<sub>Added to Mudlet in an unreleased 2.0rc8</sub>
+
registerAnonymousEventHandler("sysIrcMessage", onIrcMessage)
 +
</syntaxhighlight>
 +
 
 +
To send a message, see [[Manual:Networking_Functions#sendIrc|sendIrc()]].
 +
 
 +
===sysLabelDeleted===
 +
 
 +
Raised after a label is deleted, with the former label's name as an argument.
 +
 
 +
 
 +
===sysLoadEvent===
 +
 
 +
Raised after Mudlet is done loading the profile, after all of the scripts, packages, and modules are installed. Note that when it does so, it also compiles and runs all scripts - which could be a good idea to initialize everything at once, but beware - scripts are also run when saved. Hence, hooking only on the sysLoadEvent would prevent multiple re-loads as you’re editing the script.
 +
 
 +
===sysLuaInstallModule===
 +
 
 +
Raised right after a module is installed through the Lua installModule() command. This can be used to display post-installation information or setup things.
 +
 
 +
Event handlers receive the name of the installed module as well as the file name as additional arguments.
 +
 
 +
{{MudletVersion|3.1}}
 +
 
 +
===sysLuaUninstallModule===
 +
 
 +
Raised right before a module is removed through the lua uninstallModule command. This can be used to display post-removal information or for cleanup.
 +
 
 +
Event handlers receive the name of the removed module as additional argument.
 +
 
 +
{{MudletVersion|3.1}}
 +
 
 +
===sysManualLocationSetEvent===
 +
 
 +
Raised whenever the "set location" command (on the 2D mapper context menu) is used to reposition the current "player room".  It provides the room ID of the new room ID that the player has been moved to.
 +
 
 +
{{MudletVersion|3.0}}
 +
 
 +
===sysMapAreaChanged===
 +
Raised whenever the area being viewed in the mapper changes, it returns two additional arguments being the areaID numbers being changed to and the previously viewed area.
  
===sysDataSendRequest===
+
{{MudletVersion|4.17.0}}
Raised right before a command from the send() function or the command line is sent to the game - useful for keeping track of what your last command was, or even denying the command to be sent if necessary with ''denyCurrentSend()''.
+
 
 +
===sysMapDownloadEvent===
 +
 
 +
Raised whenever an [[Standards:MMP|MMP map]] is downloaded and loaded in.
 +
 
 +
===sysMediaFinished===
 +
 
 +
Raised when media finishes playing. This can be used in a music player for example to start the next song.
 +
 
 +
Event handlers receive the media file name and the file path as additional arguments.
 +
 
 +
{{MudletVersion|4.15}}
 +
 
 +
===sysPathChanged===
 +
 
 +
Raised whenever file or directory added through [[Manual:Lua_Functions#addFileWatch|addFileWatch()]] is modified.
 +
 
 +
For directories this event is emitted when the directory at a specified path is modified (e.g., when a file is added or deleted) or removed from disk. Note that if there are several changes during a short period of time, some of the changes might not emit this signal. However, the last change in the sequence of changes will always generate this signal.
 +
 
 +
For files this event is emitted when the file at the specified path is modified, renamed or removed from disk.
  
Note: if you'll be making use of denyCurrentSend(), you ''really should'' notify the user that you denied their command - unexperienced ones might conclude that your script or Mudlet is buggy if they don't see visual feedback. Do not mis-use this and use it as [http://en.wikipedia.org/wiki/Keylogger keylogger] either.
+
{{MudletVersion|4.12}}
  
<lua>
+
;Example
function onNetworkOutput(_, command)
+
<syntaxhighlight lang="lua">
   if math.random(2) == 1 then
+
herbs = {}
     echo("Hello! Sending "..command.." to the game.\n")
+
local herbsPath = getMudletHomeDir() .. "/herbs.lua"
  else
+
function herbsChangedHandler(_, path)
     echo("Not your day! Denying "..command..".\n")
+
   if path == herbsPath then
 +
     table.load(herbsPath, herbs)
 +
     removeFileWatch(herbsPath)
 
   end
 
   end
 
end
 
end
</lua>
 
  
===sysConnectionEvent===
+
addFileWatch(herbsPath)
Raised when the profile becomes connected to a MUD - available in 2.0-test5+.
+
registerAnonymousEventHandler("sysPathChanged", herbsChangedHandler)
 +
</syntaxhighlight>
 +
 
 +
===sysPostHttpDone===
 +
 
 +
Raised whenever a [[Manual:Networking_Functions#postHTTP|postHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).
 +
 
 +
See also [[#sysPostHttpError|sysPostHttpError]].
 +
 
 +
===sysPostHttpError===
 +
 
 +
Raised whenever a [[Manual:Networking_Functions#postHTTP|postHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.
 +
 
 +
See also [[#sysPostHttpDone|sysPostHttpDone]].
  
===sysDisconnectionEvent===
+
===sysProfileFocusChangeEvent===
Raised when the profile becomes disconnected, either manually or by the game - available in 2.0-test5+.
 
  
===sysTelnetEvent===
+
:Raised whenever a profile becomes or stops being the foreground one when multi-playing, whether multi-view (show all profiles side-by-side) is active or not. The event comes with a second ''boolean'' argument which is ''true'' if the profile is now the one that has the focus, i.e. will receive keystrokes entered from the keyboard, or ''false'' if the focus has just switched from it to another profile.
Raised whenever an unsupported telnet option is encountered, allowing you to handle it yourself. The arguments that get passed with the event are type, telnet option, and the message. Available in 2.1+
 
  
===sysMapDownloadEvent===
+
{{MudletVersion|4.17.0}}
Raised whenever an MMP map (currently only supported by IRE games) is downloaded and loaded in.
 
  
 
===sysProtocolDisabled===
 
===sysProtocolDisabled===
Raised whenever a communications protocol is disabled, with the protocol name passed as an argument. Current values Mudlet will use for this are: GMCP, MDSP, ATCP, GMCP, MXP, and channel102.
+
 
 +
Raised whenever a communications protocol is disabled, with the protocol name passed as an argument. Current values Mudlet will use for this are: GMCP, MDSP, ATCP, MXP, and channel102.
  
 
===sysProtocolEnabled===
 
===sysProtocolEnabled===
 +
 
Raised whenever a communications protocol is enabled, with the protocol name passed as an argument. Current values Mudlet will use for this are: GMCP, MDSP, ATCP, MXP, and channel102.
 
Raised whenever a communications protocol is enabled, with the protocol name passed as an argument. Current values Mudlet will use for this are: GMCP, MDSP, ATCP, MXP, and channel102.
  
<lua>
+
<syntaxhighlight lang="lua">
 
function onProtocolEnabled(_, protocol)
 
function onProtocolEnabled(_, protocol)
 
   if protocol == "GMCP" then
 
   if protocol == "GMCP" then
Line 181: Line 547:
 
   end
 
   end
 
end
 
end
</lua>
+
</syntaxhighlight>
 +
 
 +
===sysPutHttpDone===
 +
 
 +
Raised whenever a [[Manual:Networking_Functions#putHTTP|putHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).
 +
 
 +
See also [[#sysPutHttpError|sysPutHttpError]].
 +
 
 +
===sysPutHttpError===
 +
 
 +
Raised whenever a [[Manual:Networking_Functions#putHTTP|putHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.
 +
 
 +
See also [[#sysPutHttpDone|sysPutHttpDone]].
 +
 
 +
===sysSoundFinished===
 +
 
 +
This event is obsolete in Mudlet 4.15. Please replace this with [[Manual:Event_Engine#sysMediaFinished|sysMediaFinished()]]
 +
 
 +
{{MudletVersion|3.1}}
 +
 
 +
===sysSpeedwalkFinished===
 +
 
 +
Raised when a speedwalk finishes, either one started by speedwalk() or the generic mapping script
 +
 
 +
===sysSpeedwalkPaused===
 +
 
 +
Raised when a speedwalk is paused, either via pauseSpeedwalk() or the generic mapping script.
 +
 
 +
===sysSpeedwalkResumed===
 +
 
 +
Raised when a speedwalk is resumed after pausing, whether it's the generic mapping script or the resumeSpeedwalk() function
 +
 
 +
===sysSpeedwalkStarted===
 +
 
 +
Raised when a speedwalk is started, either by the speedwalk() function or the generic mapping script
 +
 
 +
===sysSpeedwalkStopped===
 +
 
 +
Raised when a speedwalk is stopped prematurely by stopSpeedwalk() or the generic mapping script
 +
 
 +
===sysSyncInstallModule===
 +
 
 +
Raised right after a module is installed through the "sync" mechanism. This can be used to display post-installation information or setup things.
 +
 
 +
Event handlers receive the name of the installed module as well as the file name as additional arguments.
 +
 
 +
{{MudletVersion|3.1}}
 +
 
 +
===sysSyncUninstallModule===
 +
 
 +
Raised right before a module is removed through the "sync" mechanism. This can be used to display post-removal information or for cleanup.
 +
 
 +
Event handlers receive the name of the removed module as additional argument.
 +
 
 +
{{MudletVersion|3.1}}
 +
 
 +
===sysTelnetEvent===
 +
 
 +
Raised whenever an unsupported telnet option is encountered, allowing you to handle it yourself. The arguments that get passed with the event are type, telnet option, and the message.
 +
 
 +
===sysUninstall===
 +
 
 +
Raised right before a module or package is uninstalled by any means. This can be used to display post-removal information or for cleanup.
 +
 
 +
Event handlers receive the name of the removed package or module as additional argument.
 +
 
 +
{{MudletVersion|3.1}}
 +
 
 +
===sysUninstallModule===
 +
 
 +
Raised right before a module is removed through the module dialog. This can be used to display post-removal information or for cleanup.
 +
 
 +
Event handlers receive the name of the removed module as additional argument.
 +
 
 +
{{MudletVersion|3.1}}
 +
 
 +
===sysUninstallPackage===
 +
 
 +
Raised right before a package is removed by any means. This can be used to display post-removal information or for cleanup.
 +
 
 +
Event handlers receive the name of the removed package as additional argument.
 +
 
 +
{{MudletVersion|3.1}}
 +
 
 +
===sysUnzipDone===
 +
 
 +
Raised when a zip file is successfully unzipped using unzipAsync()
 +
 
 +
Event handlers receive the zip file name and the unzip path as additional arguments.
 +
 
 +
{{MudletVersion|4.6}}
 +
 
 +
===sysUnzipError===
 +
 
 +
Raised when a zip file fails to unzip using unzipAsync()
 +
 
 +
Event handlers receive the zip file name and the unzip path as additional arguments.
 +
 
 +
{{MudletVersion|4.6}}
 +
 
 +
===sysUserWindowResizeEvent===
 +
 
 +
Raised when a userwindow is resized, with the new height and width coordinates and the windowname passed to the event. A common usecase for this event is to move/resize your UI elements according to the new dimensions.
 +
 
 +
See alsoː [[#sysWindowResizeEvent|sysWindowResizeEvent]]
 +
 
 +
Example
 +
 
 +
This sample code will echo whenever a resize happened with the new dimensions:
 +
 
 +
<syntaxhighlight lang="lua">
 +
function resizeEvent( event, x, y, windowname )
 +
  echo("RESIZE EVENT: event="..event.." x="..x.." y="..y.." windowname="..windowname.."\n")
 +
end
 +
</syntaxhighlight>
 +
 
 +
===sysWindowMousePressEvent===
 +
 
 +
Raised when a mouse button is pressed down anywhere on the main window (note that a click is composed of a mouse press and mouse release). The button number, the x,y coordinates of the click and the windowname are reported.
 +
 
 +
{{note}}Windowname reported in Mudlet 4.9+
 +
 
 +
See alsoː [[#sysWindowMouseReleaseEvent|sysWindowMouseReleaseEvent]]
 +
 
 +
Example
 +
 
 +
<syntaxhighlight lang="lua">
 +
function onClickHandler( event, button, x, y, windowname )
 +
  echo("CLICK event:"..event.." button="..button.." x="..x.." y="..y.." windowname="..windowname.."\n")
 +
end
 +
</syntaxhighlight>
 +
 
 +
===sysWindowMouseReleaseEvent===
 +
 
 +
Raised when a mouse button is released after being pressed down anywhere on the main window (note that a click is composed of a mouse press and mouse release).
 +
 +
See [[#sysWindowMousePressEvent|sysWindowMousePressEvent]] for example use.
 +
 
 +
===sysWindowResizeEvent===
 +
 
 +
Raised when the main window is resized, or when one of the borders is resized, with the new height and width coordinates passed to the event. A common usecase for this event is to move/resize your UI elements according to the new dimensions.
 +
 
 +
See alsoː [[#sysUserWindowResizeEvent|sysUserWindowResizeEvent]]
 +
 
 +
Example
 +
 
 +
This sample code will echo whenever a resize happened with the new dimensions:
 +
 
 +
<syntaxhighlight lang="lua">
 +
function resizeEvent( event, x, y )
 +
  echo("RESIZE EVENT: event="..event.." x="..x.." y="..y.."\n")
 +
end
 +
</syntaxhighlight>
 +
 
 +
===ttsPitchChanged===
 +
 
 +
Raised when text-to-speech function [[Manual:Lua_Functions#ttsSetPitch|ttsSetPitch(...)]] has been called.
 +
 
 +
See also: [[Manual:Text-to-Speech]]
 +
 
 +
===ttsRateChanged===
 +
 
 +
Raised when text-to-speech function [[Manual:Lua_Functions#ttsSetRate|ttsSetRate(...)]] has been called.
 +
 
 +
See also: [[Manual:Text-to-Speech]]
 +
 
 +
===ttsSpeechError===
 +
 
 +
Raised when a text-to-speech function encountered an error while changing states (eg. from [[Manual:Lua_Functions#ttsStop|stopped]] to [[Manual:Lua_Functions#ttsPlay|playing]] to [[Manual:Lua_Functions#ttsPause|pausing]]).  Usually indicated when the operating system TTS engine is not working correctly.
 +
 
 +
See also: [[Manual:Text-to-Speech]]
 +
 
 +
===ttsSpeechPaused===
 +
 
 +
Raised when text-to-speech function [[Manual:Lua_Functions#ttsSetPitch|ttsPause(...)]] has been called.
 +
 
 +
See also: [[Manual:Text-to-Speech]]
 +
 
 +
===ttsSpeechQueued===
 +
 
 +
Raised when text-to-speech function [[Manual:Lua_Functions#ttsQueue|ttsQueue(...)]] has been called.
 +
 
 +
See also: [[Manual:Text-to-Speech]]
 +
 
 +
===ttsSpeechReady===
 +
 
 +
Raised when the text-to-speech engine is ready to beginning processing text.
 +
 
 +
See also: [[Manual:Text-to-Speech]]
 +
 
 +
===ttsSpeechStarted===
 +
 
 +
Raised when text-to-speech functions [[Manual:Lua_Functions#ttsSpeak|ttsSpeak(...)]] or [[Manual:Lua_Functions#ttsResume|ttsResume(...)]] have been called.
 +
 
 +
See also: [[Manual:Text-to-Speech]]
 +
 
 +
===ttsVoiceChanged===
 +
 
 +
Raised when text-to-speech functions [[Manual:Lua_Functions#ttsSetVoiceByIndex|ttsSetVoiceByIndex(...)]] or [[Manual:Lua_Functions#ttsSetVoiceByName|ttsSetVoiceByName(...)]] have been called.
 +
 
 +
See also: [[Manual:Text-to-Speech]]
 +
 
 +
===ttsVolumeChanged===
 +
 
 +
Raised when text-to-speech function [[Manual:Lua_Functions#ttsSetVolume|ttsSetVolume(...)]] has been called.
  
 +
See also: [[Manual:Text-to-Speech]]
 
[[Category:Mudlet Manual]]
 
[[Category:Mudlet Manual]]

Latest revision as of 21:37, 30 October 2024

Event System

Events in Mudlet allow a paradigm of system-building that is easy to maintain (because if you’d like to restructure something, you’d have to do less work), enables interoperability (making a collection of scripts that work with each other is easier) and enables an event-based way of programming.

The essentials of it are as such: you use Scripts to define which events a function should listen to, and when the event is raised, the said function(s) will be called. Events can also have function parameters with them, which’ll be passed onto the receiving functions.

Registering an event handler via UI

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

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

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

Gui-event-handler.png

Registering an event from a script

You can also register your event with the registerAnonymousEventHandler(event name, function reference, [one shot]) function inside your scripts:

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

registerAnonymousEventHandler("sysWindowResizeEvent", keepStaticSize, false)

Note Note: : registerNamedEventHandler can also be used. Doing so causes Mudlet to handle saving of the IDs for you.

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

Raising a custom event

To raise an event, you'd use the raiseEvent() function:

raiseEvent(name, [arguments...])

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

Example of registering and raising an event

Add a script to each profile you need the event.

-- This is the function that will be called when the event is raised.
-- "event" is set to the event name.
-- "arg" is the argument(s) provided with raiseEvent/raiseGlobalEvent.
-- "profile" - Is the profile name from where the raiseGlobalEvent was triggered from
--             It is 'nil' if raiseEvent() was used.
function onMyEvent(event, arg, profile)
  echo("Event: " .. event .. "\n")
  echo("Arg  : " .. arg .. "\n")
  -- If the event is not raised with raiseGlobalEvent() profile will be 'nil'
  echo("Profile: " .. (profile or "Local") .. "\n")
end

-- Register the event handler.
registerAnonymousEventHandler("my_event", onMyEvent)

To raise the event you can call:

-- Trigger only in the current profile:
raiseEvent("my_event", "Hello world!")

-- Trigger the event in all OTHER profiles:
raiseGlobalEvent("my_event", "Hello World!")

To review, count and extract from an unknown number of arguments received by an event:

function eventArgs(...)
  local args = {...}
  local amount = #args
  local first = args[1]
  echo("Number of arguments: " .. amount)
  echo("\nTable of all arguments: ")
  display(args)
  echo("First argument: " .. first)
  echo("\n\n")
end

Gamepad functionality

Note Note: will be removed in 4.18 as this is blocking Mudlet updates and is not used by players.

Gamepad functions are not fully supported with all operating systems and hardware. Windows supports XInput devices like Xbox 360 and Xbox One controllers. DirectInput controllers like a PlayStation 4 controller can be translated to XInput with third party software. Mudlet on Linux can support gamepads but only if you compile it yourself. The automated builds are made using the oldest supported version of Ubuntu, and the Qt5 gamepad module was not available on Ubuntu 18.04 LTS.

Mudlet-raised events

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

AdjustableContainerReposition

Raised while a adjustable container is re-positioned.

function repositioningContainer(eventName, containerName, width, height, x, y, mouseAction)
  print(f"{containerName}: {x}x, {y}y, {width}x{height}, using mouse? {mouseAction}")
end

registerAnonymousEventHandler("AdjustableContainerReposition", repositioningContainer)

AdjustableContainerRepositionFinish

Raised when an adjustable container done being re-positioned.

function finishedRepositioning(eventName, containerName, width, height, x, y)
  print(f"{containerName}: {x}x, {y}y, {width}x{height}")
end

registerAnonymousEventHandler("AdjustableContainerRepositionFinish", finishedRepositioning)

channel102Message

Raised when a telnet sub-option 102 message is received (which comprises of two numbers passed in the event). This is of particular use with the Aardwolf MUD who originated this protocol. See this forum topic for more about the Mudlet Aardwolf GUI that makes use of this.

mapModeChangeEvent

Raised when the mapper is switching between "view-only" and "editing" mode of the Visual Map Editor. A value of "editing" or "viewing" will be given as argument to indicate which mode was entered.

mapOpenEvent

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

sysAppStyleSheetChange

Raised when setAppStyleSheet is called and a new stylesheet applied to Mudlet.

-- This will respond to a future (as yet unpublished) addition to the Mudlet code that will allow some
-- of a default application style sheet to be supplied with Mudlet to compensate for some text colors
-- that do not show up equally well in both light and dark desktop themes. That, perhaps, might finally
-- allow different colored texts to be uses again for the trigger item types!
function appStyleSheetChangeEvent( event, tag, source )
  if source == "system" then
    colorTable = colorTable or {}
    if tag == "mudlet-dark-theme" then
      colorTable.blue = {64, 64, 255}
      colorTable.green = {0, 255, 0}
    elseif tag == "mudlet-light-theme" then
      colorTable.blue = {0, 0, 255}
      colorTable.green = {64, 255, 64}
    end
  end
end
Mudlet VersionAvailable in Mudlet3.19+

sysBufferShrinkEvent

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

Mudlet VersionAvailable in Mudlet4.17+

sysConnectionEvent

Raised when the profile becomes connected to a MUD.

sysCustomHttpDone

Raised whenever a customHTTP() request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters) and HTTP method.

See also sysCustomHttpError.

sysCustomHttpError

Raised whenever a customHTTP() request fails. Arguments are the error message and the URL that the request was sent to and HTTP method.

See also sysCustomHttpDone.

sysDataSendRequest

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

sysDataSendRequest will send the event name and the command sent (in string form) to the functions registered to it. IE: commandSent in the example below will be "eat hambuger" if the user entered only that into command line and pressed enter, send("eat hamburger"), sendAll("eat humburger", "eat fish") or sendAll("eat fish", "eat humburger")

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

-- cancels all "eat hambuger" commands
function cancelEatHamburger(eventName, commandSent)
  if commandSent == "eat hamburger" then
    denyCurrentSend() --cancels the command sent.
    cecho("<red>Denied! You can't do "..commandSent.." right now.\n")
  end --if commandSent == eat hamburger
end

registerAnonymousEventHandler("sysDataSendRequest", cancelEatHamburger)

If you wanted to control input you could set a bool after a trigger. This is useful if you want alias like control, do not know what text will be entered, but do know a trigger that WILL occur just before the user enters the command.

function controlInput(_, command) 
  if changeCMDInput then
    changeCMDInput = false --set this if check to false to it doesn't occur every input
    --Also set the bool check BEFORE any send() functions within a sysDataSendRequest function
    sendAll(command .. "some target", command .. "some other target", true) --Duplicate and unknown command
    denyCurrentSend() --Deny the original command, not the commands sent with sendAll.
  end
end
registerAnonymousEventHandler("sysDataSendRequest", controlInput)

Take note that functions registered under sysDataSendRequest WILL trigger with ALL commands that are sent.

sysDeleteHttpDone

Raised whenever a deleteHTTP() request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).

See also sysDeleteHttpError.

sysDeleteHttpError

Raised whenever a deleteHTTP() request fails. Arguments are the error message and the URL that the request was sent to.

See also sysDeleteHttpDone.

sysDisconnectionEvent

Raised when the profile becomes disconnected, either manually or by the game.

If you'd like to automatically reconnect when you get disconnected, make a new Script and add this inside:

registerAnonymousEventHandler("sysDisconnectionEvent", reconnect)

sysDownloadDone

Raised when Mudlet is finished downloading a file successfully - the location of the downloaded file is passed as a second argument, the file size is passed as the third, and the HTTP response is passed as the fourth.

Example - put it into a new script and save it to run:

-- create a function to parse the downloaded webpage and display a result
function downloaded_file(_, filename)
  -- is the file that downloaded ours?
  if not filename:find("achaea-who-count.html", 1, true) then return end

  -- read the contents of the webpage in
  local f, s, webpage = io.open(filename)
  if f then webpage = f:read("*a"); io.close(f) end
  -- delete the file on disk, don't clutter
  os.remove(filename)

  -- parse our downloaded file for the player count
  local pc = webpage:match([[Total: (%d+) players online]])
  display("Achaea has "..tostring(pc).." players on right now.")
end

-- register our function to run on the event that something was downloaded
registerAnonymousEventHandler("sysDownloadDone", downloaded_file)

-- download a list of fake users for a demo
downloadFile(getMudletHomeDir().."/achaea-who-count.html", "https://www.achaea.com/game/who")

You should see a result like this:

DownloadFile demo.png

sysDownloadError

Raised when downloading a file failed - the second argument contains the error message, the third the local filename that was to be used and the actual URL used (might not be the same as what was given if redirection took place).

Example
--if a download fails notify the player.
function downloadErrorEventHandler(event, errorFound, localFilename, usedUrl)
    cecho("fuction downloadErrorEventHandler, "..errorFound)
    debugc("fuction downloadErrorEventHandler, "..errorFound) --display to error screen in editor
end --function downloadErrorEventHandler
registerAnonymousEventHandler("sysDownloadError", downloadErrorEventHandler)

sysDownloadFileProgress

Raised while file is being downloaded to indicate progess of download.

The arguments passed areː: event name, url of download, bytes downloaded, total bytes (if available).

Example
-- will show progress bar while download file and hide it after file download is complete
local progressBar = Geyser.Gauge:new({
  name="downloadProgressBar",
  x="25%", y="10%",
  width="50%", height="5%",
})
progressBar:setFontSize(13)
progressBar:setAlignment("center")
progressBar:hide()


local fileUrl = "https://www.mudlet.org/download/Mudlet-4.10.1-linux-x64.AppImage.tar"
local targetFile = getMudletHomeDir() .. "/Mudlet.tar"
function handleProgress(_, url, bytesDownloaded, totalBytes)
  if url ~= fileUrl then
    return
  end
  
  progressBar:show()
  
  if not totalBytes then
    bytesDownloaded = 0
    totalBytes = 1
  end
  
  progressBar:setValue(bytesDownloaded, totalBytes, math.floor((bytesDownloaded / totalBytes) * 100) .. "%")
end

registerAnonymousEventHandler("sysDownloadFileProgress", handleProgress)

function hideProgressBar()
  tempTimer(3, function() progressBar:hide() end)
end 

registerAnonymousEventHandler("sysDownloadDone", hideProgressBar)
registerAnonymousEventHandler("sysDownloadError", hideProgressBar)

downloadFile(targetFile, fileUrl)
Mudlet VersionAvailable in Mudlet4.11+

sysDropEvent

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

Mudlet VersionAvailable in Mudlet4.8+
function onDragAndDrop(_, filepath, suffix, xpos, ypos, consolename)
  print(string.format("Dropped new file into %s: %s (suffix: %s)", consolename, filepath, suffix))
end
registerAnonymousEventHandler("sysDropEvent", onDragAndDrop)

sysDropUrlEvent

Raised when a url is dropped on the Mudlet main window or a userwindow. As an url at the moment Mudlet understands The arguments passed areː url, schema, xpos, ypos, and consolename - "main" for the main window and otherwise of the userwindow/miniconsole name.

Mudlet VersionAvailable in Mudlet4.11+
function onDragAndDropUrl(_, url, schema, xpos, ypos, consolename)
  print(string.format("Dropped new url into %s: %s (suffix: %s)", consolename, filepath, suffix))
  if schema == "http" or schema == "https" then
    print("\nOh boy... this might be a link to some website")
  end
end
registerAnonymousEventHandler("sysDropUrlEvent", onDragAndDropUrl)

sysExitEvent

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

sysGetHttpDone

Raised whenever a getHTTP() request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).

This event is also raised when a post/put/delete request redirects to a GET.

See also sysGetHttpError.

Mudlet VersionAvailable in Mudlet4.10+

sysGetHttpError

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

See also sysGetHttpDone.

Mudlet VersionAvailable in Mudlet4.10+

sysInstall

Raised right after a module or package is installed by any means. This can be used to display post-installation information or setup things.

Event handlers receive the name of the installed package or module as additional argument.

Note Note: Installed modules will raise this event handler each time the synced profile is opened. sysInstallModule and sysInstallPackage are not raised by opening profiles.

Mudlet VersionAvailable in Mudlet3.1+
function myScriptInstalled(_, name)
  -- stop if what got installed isn't my thing
  if name ~= "my script name here" then return end

  print("Hey, thanks for installing my thing!")
end
registerAnonymousEventHandler("sysInstallPackage", myScriptInstalled)

sysInstallModule

Raised right after a module is installed through the module dialog. This can be used to display post-installation information or setup things.

See also sysLuaInstallModule for when a module is installed via Lua.

Event handlers receive the name of the installed module as well as the file name as additional arguments.

Mudlet VersionAvailable in Mudlet3.1+

sysInstallPackage

Raised right after a package is installed by any means. This can be used to display post-installation information or setup things.

Event handlers receive the name of the installed package as well as the file name as additional arguments.

Mudlet VersionAvailable in Mudlet3.1+

sysIrcMessage

Raised when the IRC client receives an IRC message. The sender's name, channel name, and their message are passed as arguments to this event.

Starting with Mudlet 3.3, this event changes slightly to provide more information from IRC network messages. Data such as status codes, command responses, or error messages sent by the IRC Server may be formatted as plain text by the client and posted to lua via this event.

  • sender: may be the nick name of an IRC user or the name of the IRC server host, as retrievable by getIrcConnectedHost()
  • channel: may not always contain a channel name, but will be the name of the target/recipient of a message or action. In some networks the name may be that of a service (like "Auth" for example)
Example
function onIrcMessage(_, sender, target, message)
  echo(string.format('(%s) %s says, "%s"\n', target, sender, message))
end

registerAnonymousEventHandler("sysIrcMessage", onIrcMessage)

To send a message, see sendIrc().

sysLabelDeleted

Raised after a label is deleted, with the former label's name as an argument.


sysLoadEvent

Raised after Mudlet is done loading the profile, after all of the scripts, packages, and modules are installed. Note that when it does so, it also compiles and runs all scripts - which could be a good idea to initialize everything at once, but beware - scripts are also run when saved. Hence, hooking only on the sysLoadEvent would prevent multiple re-loads as you’re editing the script.

sysLuaInstallModule

Raised right after a module is installed through the Lua installModule() command. This can be used to display post-installation information or setup things.

Event handlers receive the name of the installed module as well as the file name as additional arguments.

Mudlet VersionAvailable in Mudlet3.1+

sysLuaUninstallModule

Raised right before a module is removed through the lua uninstallModule command. This can be used to display post-removal information or for cleanup.

Event handlers receive the name of the removed module as additional argument.

Mudlet VersionAvailable in Mudlet3.1+

sysManualLocationSetEvent

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

Mudlet VersionAvailable in Mudlet3.0+

sysMapAreaChanged

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

Mudlet VersionAvailable in Mudlet4.17.0+

sysMapDownloadEvent

Raised whenever an MMP map is downloaded and loaded in.

sysMediaFinished

Raised when media finishes playing. This can be used in a music player for example to start the next song.

Event handlers receive the media file name and the file path as additional arguments.

Mudlet VersionAvailable in Mudlet4.15+

sysPathChanged

Raised whenever file or directory added through addFileWatch() is modified.

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

For files this event is emitted when the file at the specified path is modified, renamed or removed from disk.

Mudlet VersionAvailable in Mudlet4.12+
Example
herbs = {}
local herbsPath = getMudletHomeDir() .. "/herbs.lua"
function herbsChangedHandler(_, path)
  if path == herbsPath then
    table.load(herbsPath, herbs)
    removeFileWatch(herbsPath)
  end
end

addFileWatch(herbsPath)
registerAnonymousEventHandler("sysPathChanged", herbsChangedHandler)

sysPostHttpDone

Raised whenever a postHTTP() request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).

See also sysPostHttpError.

sysPostHttpError

Raised whenever a postHTTP() request fails. Arguments are the error message and the URL that the request was sent to.

See also sysPostHttpDone.

sysProfileFocusChangeEvent

Raised whenever a profile becomes or stops being the foreground one when multi-playing, whether multi-view (show all profiles side-by-side) is active or not. The event comes with a second boolean argument which is true if the profile is now the one that has the focus, i.e. will receive keystrokes entered from the keyboard, or false if the focus has just switched from it to another profile.
Mudlet VersionAvailable in Mudlet4.17.0+

sysProtocolDisabled

Raised whenever a communications protocol is disabled, with the protocol name passed as an argument. Current values Mudlet will use for this are: GMCP, MDSP, ATCP, MXP, and channel102.

sysProtocolEnabled

Raised whenever a communications protocol is enabled, with the protocol name passed as an argument. Current values Mudlet will use for this are: GMCP, MDSP, ATCP, MXP, and channel102.

function onProtocolEnabled(_, protocol)
  if protocol == "GMCP" then
    print("GMCP enabled! Now we can use GMCP data.")
  end
end

sysPutHttpDone

Raised whenever a putHTTP() request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).

See also sysPutHttpError.

sysPutHttpError

Raised whenever a putHTTP() request fails. Arguments are the error message and the URL that the request was sent to.

See also sysPutHttpDone.

sysSoundFinished

This event is obsolete in Mudlet 4.15. Please replace this with sysMediaFinished()

Mudlet VersionAvailable in Mudlet3.1+

sysSpeedwalkFinished

Raised when a speedwalk finishes, either one started by speedwalk() or the generic mapping script

sysSpeedwalkPaused

Raised when a speedwalk is paused, either via pauseSpeedwalk() or the generic mapping script.

sysSpeedwalkResumed

Raised when a speedwalk is resumed after pausing, whether it's the generic mapping script or the resumeSpeedwalk() function

sysSpeedwalkStarted

Raised when a speedwalk is started, either by the speedwalk() function or the generic mapping script

sysSpeedwalkStopped

Raised when a speedwalk is stopped prematurely by stopSpeedwalk() or the generic mapping script

sysSyncInstallModule

Raised right after a module is installed through the "sync" mechanism. This can be used to display post-installation information or setup things.

Event handlers receive the name of the installed module as well as the file name as additional arguments.

Mudlet VersionAvailable in Mudlet3.1+

sysSyncUninstallModule

Raised right before a module is removed through the "sync" mechanism. This can be used to display post-removal information or for cleanup.

Event handlers receive the name of the removed module as additional argument.

Mudlet VersionAvailable in Mudlet3.1+

sysTelnetEvent

Raised whenever an unsupported telnet option is encountered, allowing you to handle it yourself. The arguments that get passed with the event are type, telnet option, and the message.

sysUninstall

Raised right before a module or package is uninstalled by any means. This can be used to display post-removal information or for cleanup.

Event handlers receive the name of the removed package or module as additional argument.

Mudlet VersionAvailable in Mudlet3.1+

sysUninstallModule

Raised right before a module is removed through the module dialog. This can be used to display post-removal information or for cleanup.

Event handlers receive the name of the removed module as additional argument.

Mudlet VersionAvailable in Mudlet3.1+

sysUninstallPackage

Raised right before a package is removed by any means. This can be used to display post-removal information or for cleanup.

Event handlers receive the name of the removed package as additional argument.

Mudlet VersionAvailable in Mudlet3.1+

sysUnzipDone

Raised when a zip file is successfully unzipped using unzipAsync()

Event handlers receive the zip file name and the unzip path as additional arguments.

Mudlet VersionAvailable in Mudlet4.6+

sysUnzipError

Raised when a zip file fails to unzip using unzipAsync()

Event handlers receive the zip file name and the unzip path as additional arguments.

Mudlet VersionAvailable in Mudlet4.6+

sysUserWindowResizeEvent

Raised when a userwindow is resized, with the new height and width coordinates and the windowname passed to the event. A common usecase for this event is to move/resize your UI elements according to the new dimensions.

See alsoː sysWindowResizeEvent

Example

This sample code will echo whenever a resize happened with the new dimensions:

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

sysWindowMousePressEvent

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

Note Note: Windowname reported in Mudlet 4.9+

See alsoː sysWindowMouseReleaseEvent

Example

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

sysWindowMouseReleaseEvent

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

See sysWindowMousePressEvent for example use.

sysWindowResizeEvent

Raised when the main window is resized, or when one of the borders is resized, with the new height and width coordinates passed to the event. A common usecase for this event is to move/resize your UI elements according to the new dimensions.

See alsoː sysUserWindowResizeEvent

Example

This sample code will echo whenever a resize happened with the new dimensions:

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

ttsPitchChanged

Raised when text-to-speech function ttsSetPitch(...) has been called.

See also: Manual:Text-to-Speech

ttsRateChanged

Raised when text-to-speech function ttsSetRate(...) has been called.

See also: Manual:Text-to-Speech

ttsSpeechError

Raised when a text-to-speech function encountered an error while changing states (eg. from stopped to playing to pausing). Usually indicated when the operating system TTS engine is not working correctly.

See also: Manual:Text-to-Speech

ttsSpeechPaused

Raised when text-to-speech function ttsPause(...) has been called.

See also: Manual:Text-to-Speech

ttsSpeechQueued

Raised when text-to-speech function ttsQueue(...) has been called.

See also: Manual:Text-to-Speech

ttsSpeechReady

Raised when the text-to-speech engine is ready to beginning processing text.

See also: Manual:Text-to-Speech

ttsSpeechStarted

Raised when text-to-speech functions ttsSpeak(...) or ttsResume(...) have been called.

See also: Manual:Text-to-Speech

ttsVoiceChanged

Raised when text-to-speech functions ttsSetVoiceByIndex(...) or ttsSetVoiceByName(...) have been called.

See also: Manual:Text-to-Speech

ttsVolumeChanged

Raised when text-to-speech function ttsSetVolume(...) has been called.

See also: Manual:Text-to-Speech