Difference between revisions of "Manual:Mudlet Object Functions"

From Mudlet
Jump to navigation Jump to search
m (→‎stopStopWatch: revise somewhat)
 
(173 intermediate revisions by 14 users not shown)
Line 1: Line 1:
 
{{TOC right}}
 
{{TOC right}}
 +
{{#description2:Mudlet API documentation for functions to manipulate Mudlet's scripting objects - triggers, aliases, and so forth.}}
 
= Mudlet Object Functions =
 
= Mudlet Object Functions =
 +
Collection of functions to manipulate Mudlet's scripting objects - triggers, aliases, and so forth.
  
==appendCmdLine==
+
==addCmdLineSuggestion==
;appendCmdLine()
+
;addCmdLineSuggestion([name], suggestion)
: Appends text to the main input line.
+
: Add suggestion for tab completion for specified command line.
  
: See also: [[Manual:Lua_Functions#printCmdLine|printCmdLine()]]
+
: For example, start typing ''he'' and hit ''TAB'' until ''help'' appears in command line.
 +
: Non-word characters are skipped (this is the reason why they can't be added at start of suggestion), therefore it's also possible to type: ''/he'' and hit ''TAB''.
  
;Example
+
: See also: [[Manual:Lua_Functions#clearCmdLineSuggestions|clearCmdLineSuggestions()]], [[Manual:Lua_Functions#removeCmdLineSuggestion|removeCmdLineSuggestion()]]
<syntaxhighlight lang="lua">
 
-- adds the text "55 backpacks" to whatever is currently in the input line
 
appendCmdLine("55 backpacks")
 
  
-- makes a link, that when clicked, will add "55 backpacks" to the input line
+
{{MudletVersion|4.11}}
echoLink("press me", "appendCmdLine'55 backpack'", "Press me!")
 
</syntaxhighlight>
 
  
==clearCmdLine==
+
;Parameters
;clearCmdLine()
+
* ''name'': optional command line name, if skipped main command line will be used
: Clears the input line of any text that's been entered.
+
* ''suggestion'' - suggestion as a single word to add to tab completion (only the following are allowed: ''0-9A-Za-z_'')
  
;Example
+
Example:
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- don't be evil with this!
+
addCmdLineSuggestion("help")
clearCmdLine()
+
 
 +
local suggestions = {"Pneumonoultramicroscopicsilicovolcanoconiosis", "supercalifragilisticexpialidocious", "serendipitous"}
 +
for _, suggestion in ipairs(suggestions) do
 +
  addCmdLineSuggestion(suggestion)
 +
end
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==createStopWatch==
+
==adjustStopWatch==
;createStopWatch()
+
;adjustStopWatch(watchID/watchName, amount)
;createStopWatch([name]) from TBA
+
: Adjusts the elapsed time on the stopwatch forward or backwards by the amount of time. It will work even on stopwatches that are not running, and thus can be used to preset a newly created stopwatch with a negative amount so that it runs down from a negative time towards zero at the preset time.
: This function creates a stopwatch, a high resolution time measurement tool. Stopwatches can be started, stopped, reset, asked how much time has passed since the stop watch has been started and, pending an update due for Mudlet TBA: be adjusted, given a name and be made persistent between sessions (so can time real-life things).
 
  
: Returns: The ID of a stopwatch; or, from TBA: a nil + error message if the name has already been used.
+
;Parameters
 +
* watchID (number) / watchName (string): The stopwatch ID you get with [[Manual:Lua_Functions#createStopWatch|createStopWatch()]] or the name given to that function or later set with [[Manual:Lua_Functions#setStopWatchName|setStopWatchName()]].
 +
* amount (decimal number): An amount in seconds to adjust the stopwatch by, positive amounts increase the recorded elapsed time.
  
: See also: [[Manual:Lua_Functions#startStopWatch|startStopWatch()]], [[Manual:Lua_Functions#stopStopWatch|stopStopWatch()]], [[Manual:Lua_Functions#resetStopWatch|resetStopWatch()]], [[Manual:Lua_Functions#getStopWatchTime|getStopWatchTime()]] or, from TBA: [[Manual:Lua_Functions#adjustStopWatch|adjustStopWatch()]], [[Manual:Lua_Functions#destroyStopWatch|destroyStopWatch()]], [[Manual:Lua_Functions#getStopWatches|getStopWatches()]], [[Manual:Lua_Functions#getStopWatchBrokenDownTime|getStopWatchBrokenDownTime()]], [[Manual:Lua_Functions#setStopWatchName|setStopWatchName()]], [[Manual:Lua_Functions#setStopWatchPersistence|setStopWatchPersistence()]]
+
;Returns
 +
* true on success if the stopwatch was found and thus adjusted, or nil and an error message if not.
  
 
;Example
 
;Example
:In a global script you can create all stop watches that you need in your system and store the respective stopWatch-IDs in global variables:
 
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
fightStopWatch = fightStopWatch or createStopWatch() -- create, or re-use a stopwatch, and store the watchID in a global variable to access it from anywhere
+
-- demo of a persistent stopWatch used to real time a mission
 +
-- called with a positive number of seconds it will start a "missionStopWatch"
 +
-- unless there already is one in which case it will instead report on
 +
-- the deadline. use 'stopStopWatch("missionStopWatch")' when the mission
 +
-- is done and 'deleteStopWatch("missionStopWatch")' when the existing mission
 +
-- is to be disposed of. Until then repeated use of 'mission(interval)' will
 +
-- just give updates...
 +
function mission(time)
 +
  local missionTimeTable = missionTimeTable or {}
  
-- then you can start the stop watch in some trigger/alias/script with:
+
  if createStopWatch("missionStopWatch") then
startStopWatch(fightStopWatch)
+
    adjustStopWatch("missionStopWatch", -tonumber(time))
 +
    setStopWatchPersistence("missionStopWatch", true)
 +
    missionTimeTable = getStopWatchBrokenDownTime("missionStopWatch")
  
-- to stop the watch and measure its time in e.g. a trigger script you can write:
+
    echo(string.format("Get cracking, you have %02i:%02i:%02i hg:m:s left.\n", missionTimeTable.hours, missionTimeTable.minutes, missionTimeTable.seconds))
fightTime = stopStopWatch(fightStopWatch)
+
    startStopWatch("missionStopWatch")
echo("The fight lasted for " .. fightTime .. " seconds.")
+
  else
resetStopWatch(fightStopWatch)
+
    -- it already exists, so instead report what is/was the time on it
 +
    --[=[ We know that the stop watch exists - we just need to find the ID
 +
      so we can get the running detail which is only available from the getStopWatches()
 +
      table and that is indexed by ID]=]
 +
    for k,v in pairs(getStopWatches()) do
 +
      if v.name == "missionStopWatch" then
 +
        missionTimeTable = v
 +
      end
 +
    end
 +
    if missionTimeTable.isRunning then
 +
      if missionTimeTable.elapsedTime.negative then
 +
        echo(string.format("Better hurry up, the clock is ticking on an existing mission and you only have %02i:%02i:%02i h:m:s left.\n", missionTimeTable.elapsedTime.hours, missionTimeTable.elapsedTime.minutes, missionTimeTable.elapsedTime.seconds))
 +
      else
 +
        echo(string.format("Bad news, you are past the deadline on an existing mission by %02i:%02i:%02i h:m:s !\n", missionTimeTable.elapsedTime.hours, missionTimeTable.elapsedTime.minutes, missionTimeTable.elapsedTime.seconds))
 +
      end
 +
    else
 +
      if missionTimeTable.elapsedTime.negative then
 +
        echo(string.format("Well done! You have already completed a mission %02i:%02i:%02i h:m:s before the deadline ...\n", missionTimeTable.elapsedTime.hours, missionTimeTable.elapsedTime.minutes, missionTimeTable.elapsedTime.seconds))
 +
      else
 +
        echo(string.format("Uh oh! You failed to meet the deadline on an existing mission by %02i:%02i:%02i h:m:s !\n", missionTimeTable.elapsedTime.hours, missionTimeTable.elapsedTime.minutes, missionTimeTable.elapsedTime.seconds))
 +
      end
 +
    end
 +
  end
 +
end
 +
 
 +
 
 +
-- in use:
 +
lua mission(60*60)
 +
Get cracking, you have 01:00:00 h:m:s left.
 +
 
 +
lua mission(60*60)
 +
Better hurry up, the clock is ticking on an existing mission and you only have 00:59:52 h:m:s left.
 
</syntaxhighlight>
 
</syntaxhighlight>
:You can also measure the elapsed time without having to stop the stop watch (equivalent to getting a ''lap-time'') with [[#getStopWatchTime|getStopWatchTime()]].
 
  
{{note}} it's best to re-use stopwatch IDs if you can for Mudlet prior to TBA as they cannot be deleted, so creating more and more would use more memory. From TBA the revised internal design has been changed such that there are no internal timers created for each stopwatch - instead either a timestamp or a fixed elapsed time record is used depending on whether the stopwatches is running or stopped so that there are no "moving parts" in the later design and less resources are used - and they can be removed if no longer required.
+
{{MudletVersion|4.4}}
 +
 
 +
==appendScript==
 +
;appendScript(scriptName, luaCode, [occurrence])
 +
: Appends Lua code to the script "scriptName". If no occurrence given it sets the code of the first found script.
  
==deleteStopWatch==
+
: See also: [[Manual:Lua_Functions#permScript|permScript()]], [[Manual:Lua_Functions#enableScript|enableScript()]], [[Manual:Lua_Functions#disableScript|disableScript()]], [[Manual:Lua_Functions#getScript|getScript()]], [[Manual:Lua_Functions#setScript|setScript()]]
;deleteStopWatch(watchID/watchName)
 
  
: This function removes an existing stopwatch, whether it only exists for this session or is set to be otherwise saved between sessions by using [[Manual:Lua_Functions#setStopWatchPersistence|setStopWatchPersistence()]] with a ''true'' argument.
+
;Returns
 +
* a unique id number for that script.
  
: Returns: ''true'' if the stopwatch was found and thus deleted, or ''nil'' and an error message if not - obviously using it twice with the same argument will fail the second time unless another one with the same name or ID was recreated before the second use.  Note that an empty string as a name ''will'' find the lowest ID numbered ''unnamed'' stopwatch and that will find the next lowest ID number, unnamed, one until there are none left if used repetitively!
+
;Parameters
 +
* ''scriptName'': name of the script
 +
* ''luaCode'': scripts luaCode to append
 +
* ''occurence'': (optional) the occurrence of the script in case you have many with the same name
  
 +
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
lua MyStopWatch = createStopWatch("stopwatch_mine")
+
-- an example of appending the script lua code to the first occurrence of "testscript"
true
+
appendScript("testscript", [[echo("This is a test\n")]], 1)
 +
</syntaxhighlight>
  
lua display(MyStopWatch)
+
{{MudletVersion|4.8}}
4
 
  
lua destroyStopWatch(MyStopWatch)
+
==appendCmdLine==
true
+
;appendCmdLine([name], text)
 +
: Appends text to the main input line.
 +
: See also: [[Manual:Lua_Functions#printCmdLine|printCmdLine()]], [[#clearCmdLine|clearCmdLine()]]
  
lua destroyStopWatch(MyStopWatch)
+
;Parameters
nil
+
* ''name'': (optional) name of the command line. If not given, the text will be appended to the main commandline.
 +
* ''text'': text to append
  
"stopwatch with id 4 not found"
 
  
lua destroyStopWatch("stopwatch_mine")
+
;Example
nil
+
<syntaxhighlight lang="lua">
 +
-- adds the text "55 backpacks" to whatever is currently in the input line
 +
appendCmdLine("55 backpacks")
  
"stopwatch with name "stopwatch_mine" not found"
+
-- makes a link, that when clicked, will add "55 backpacks" to the input line
 +
echoLink("press me", "appendCmdLine'55 backpack'", "Press me!")
 
</syntaxhighlight>
 
</syntaxhighlight>
  
: See also: [[Manual:Lua_Functions#createStopWatch|createStopWatch()]],
+
==clearCmdLine==
 
+
;clearCmdLine([name])
{{note}} Available from Mudlet version TBA.
+
: Clears the input line of any text that's been entered.
: Stopwatches that are NOT set to be '''persistent''' will be deleted automatically at the end of a session (or if [[Manual:Miscellaneous_Functions#resetProfile|resetProfile()]] is called).
+
: See also: [[Manual:Lua_Functions#printCmdLine|printCmdLine()]]
 
 
==disableAlias==
 
;disableAlias(name)
 
:Disables/deactivates the alias by its name. If several aliases have this name, they'll all be disabled. If you disable an alias group, all the aliases inside the group will be disabled as well.
 
: See also: [[#enableAlias|enableAlias()]]
 
  
 
;Parameters
 
;Parameters
* ''name:''
+
* ''name'': (optional) name of the command line. If not given, the main commandline's text will be cleared.
: The name of the alias. Passed as a string.
 
  
;Examples
+
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
--Disables the alias called 'my alias'
+
-- don't be evil with this!
disableAlias("my alias")
+
clearCmdLine()
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==disableKey==
+
==clearCmdLineSuggestions==
;disableKey(name)
+
;clearCmdLineSuggestions([name])
:Disables key a key (macro) or a key group. When you disable a key group, all keys within the group will be implicitly disabled as well.
 
  
: See also: [[#enableKey|enableKey()]]
+
: Clears all suggestions for command line.
  
;Parameters
+
: See also: [[Manual:Lua_Functions#addCmdLineSuggestion|addCmdLineSuggestion()]], [[Manual:Lua_Functions#removeCmdLineSuggestion|removeCmdLineSuggestion()]]
* ''name:''
 
: The name of the key or group to identify what you'd like to disable.
 
  
;Examples
+
;Parameter
 +
* ''name'': (optional) name of the command line. If not given the main commandline's suggestions will be cleared.
  
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- you could set multiple keys on the F1 key and swap their use as you wish by disabling and enabling them
+
clearCmdLineSuggestions()
disableKey("attack macro")
 
disableKey("jump macro")
 
enableKey("greet macro")
 
 
</syntaxhighlight>
 
</syntaxhighlight>
{{note}} From Version '''3.10'' returns ''true'' if one or more keys or groups of keys were found that matched the name given or ''false'' if not; prior to then it returns ''true'' if there were '''any''' keys - whether they matched the name or not!
 
  
==disableTimer==
+
==createStopWatch==
;disableTimer(name)
+
;createStopWatch([name], [start immediately])
:Disables a timer from running it’s script when it fires - so the timer cycles will still be happening, just no action on them. If you’d like to permanently delete it, use [[Manual:Lua_Functions#killTrigger|killTrigger]] instead.
+
;createStopWatch([start immediately])
 +
Before Mudlet 4.4.0:
 +
;createStopWatch()
 +
 
 +
: This function creates a stopwatch, a high resolution time measurement tool. Stopwatches can be started, stopped, reset, asked how much time has passed since the stop watch has been started and, following an update for Mudlet 4.4.0: be adjusted, given a name and be made persistent between sessions (so can time real-life things). Prior to 4.4.0 the function took no parameters '''and the stopwatch would start automatically when it was created'''.
  
: See also: [[#enableTimer|enableTimer()]]
+
;Parameters:
 +
* ''start immediately'' (bool) used to override the behaviour prior to Mudlet 4.4.0 so that if it is the ''only'' argument then a ''false'' value will cause the stopwatch to be created but be in a ''stopped'' state, however if a name parameter is provided then this behaviour is assumed and then a ''true'' value is required should it be desired for the stopwatch to be started on creation. This difference between the cases with and without a name argument is to allow for older scripts to continue to work with 4.4.0 or later versions of Mudlet without change, yet to allow for more functionality - such as presetting a time when the stopwatch is created but not to start it counting down until some time afterwards - to be performed as well with a named stopwatch.
  
;Parameters
+
* ''name'' (string) a ''unique'' text to use to identify the stopwatch.
* ''name:''
 
: Expects the timer ID that was returned by [[Manual:Lua_Functions#tempTimer|tempTimer]] on creation of the timer or the name of the timer in case of a GUI timer.
 
  
;Example
+
;Returns:
<syntaxhighlight lang="lua">
+
* the ID (number) of a stopwatch; or, from '''4.4.0''': a nil + error message if the name has already been used.
--Disables the timer called 'my timer'
 
disableTimer("my timer")
 
</syntaxhighlight>
 
  
==disableTrigger==
+
: See also: [[Manual:Lua_Functions#startStopWatch|startStopWatch()]], [[Manual:Lua_Functions#stopStopWatch|stopStopWatch()]], [[Manual:Lua_Functions#resetStopWatch|resetStopWatch()]], [[Manual:Lua_Functions#getStopWatchTime|getStopWatchTime()]] or, from 4.4.0: [[Manual:Lua_Functions#adjustStopWatch|adjustStopWatch()]], [[Manual:Lua_Functions#deleteStopWatch|deleteStopWatch()]], [[Manual:Lua_Functions#getStopWatches|getStopWatches()]], [[Manual:Lua_Functions#getStopWatchBrokenDownTime|getStopWatchBrokenDownTime()]], [[Manual:Lua_Functions#setStopWatchName|setStopWatchName()]], [[Manual:Lua_Functions#setStopWatchPersistence|setStopWatchPersistence()]]
;disableTrigger(name)
 
:Disables a permanent (one in the trigger editor) or a temporary trigger. When you disable a group, all triggers inside the group are disabled as well
 
  
: See also: [[#enableTrigger|enableTrigger()]]
+
;Example
 +
: (Prior to Mudlet 4.4.0) in a global script you can create all stop watches that you need in your system and store the respective stopWatch-IDs in global variables:
 +
<syntaxhighlight lang="lua">
 +
fightStopWatch = fightStopWatch or createStopWatch() -- create, or re-use a stopwatch, and store the watchID in a global variable to access it from anywhere
  
;Parameters
+
-- then you can start the stop watch in some trigger/alias/script with:
* ''name:''
+
startStopWatch(fightStopWatch)
: Expects the trigger ID that was returned by [[Manual:Lua_Functions#tempTrigger|tempTrigger]] or other temp*Trigger variants, or the name of the trigger in case of a GUI trigger.
 
  
;Example
+
-- to stop the watch and measure its time in e.g. a trigger script you can write:
<syntaxhighlight lang="lua">
+
fightTime = stopStopWatch(fightStopWatch)
-- Disables the trigger called 'my trigger'
+
echo("The fight lasted for " .. fightTime .. " seconds.")
disableTrigger("my trigger")
+
resetStopWatch(fightStopWatch)
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==enableAlias==
+
: (From Mudlet 4.4.0) in a global script you can create all stop watches that you need in your system with unique names:
;enableAlias(name)
+
<syntaxhighlight lang="lua">
:Enables/activates the alias by it’s name. If several aliases have this name, they’ll all be enabled.
+
createStopWatch("fightStopWatch") -- creates the stopwatch or returns nil+msg if it already exists
 +
 
 +
-- then you can start the stop watch (if it is not already started) in some trigger/alias/script with:
 +
startStopWatch("fightStopWatch")
  
: See also: [[#disableAlias|disableAlias()]]
+
-- to stop the watch and measure its time in e.g. a trigger script you can write:
 +
fightTime = stopStopWatch("fightStopWatch")
 +
echo("The fight lasted for " .. fightTime .. " seconds.")
 +
resetStopWatch("fightStopWatch")
 +
</syntaxhighlight>
 +
 
 +
:You can also measure the elapsed time without having to stop the stop watch (equivalent to getting a ''lap-time'') with [[#getStopWatchTime|getStopWatchTime()]].
 +
 
 +
{{note}} it's best to re-use stopwatch IDs if you can for Mudlet prior to 4.4.0 as they cannot be deleted, so creating more and more would use more memory. From 4.4.0 the revised internal design has been changed such that there are no internal timers created for each stopwatch - instead either a timestamp or a fixed elapsed time record is used depending on whether the stopwatches is running or stopped so that there are no "moving parts" in the later design and less resources are used - and they can be removed if no longer required.
 +
 
 +
==deleteAllNamedTimers==
 +
; deleteAllNamedTimers(userName)
 +
 
 +
:Deletes all named timers and prevents them from firing any more. Information is deleted and cannot be retrieved.
 +
 
 +
;See also: [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]], [[Manual:Lua_Functions#stopNamedTimer|stopNamedTimer()]]
 +
 
 +
{{MudletVersion|4.14}}
  
 
;Parameters
 
;Parameters
* ''name:''
+
* ''userName:''
: Expects the alias ID that was returned by [[Manual:Lua_Functions#tempAlias|tempAlias]] on creation of the alias or the name of the alias in case of a GUI alias.
+
: The user name the event handler was registered under.
  
 
;Example
 
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
--Enables the alias called 'my alias'
+
deleteAllNamedTimers("Demonnic") -- emergency stop or debugging situation, most likely.
enableAlias("my alias")
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==enableKey==
+
==deleteNamedTimer==
;enableKey(name)
+
; success = deleteNamedTimer(userName, handlerName)
:Enables a key (macro) or a group of keys (and thus all keys within it that aren't explicitly deactivated).
+
 
 +
:Deletes a named timer with name handlerName and prevents it from firing any more. Information is deleted and cannot be retrieved.
 +
 
 +
;See also: [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]], [[Manual:Lua_Functions#stopNamedTimer|stopNamedTimer()]]
 +
 
 +
{{MudletVersion|4.14}}
  
 
;Parameters
 
;Parameters
* ''name:''
+
* ''userName:''
: The name of the group that identifies the key.
+
: The user name the event handler was registered under.
 +
* ''handlerName:''
 +
: The name of the handler to stop. Same as used when you called [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]]
  
 +
;Returns
 +
* true if successful, false if it didn't exist
 +
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- you could use this to disable one key set for the numpad and activate another
+
local deleted = deleteNamedTimer("Demonnic", "DemonVitals")
disableKey("fighting keys")
+
if deleted then
enableKey("walking keys")
+
  cecho("DemonVitals deleted forever!!")
 +
else
 +
  cecho("DemonVitals doesn't exist and so could not be deleted.")
 +
end
 
</syntaxhighlight>
 
</syntaxhighlight>
{{note}} From Version '''3.10'' returns ''true'' if one or more keys or groups of keys were found that matched the name given or ''false'' if not; prior to then it returns ''true'' if there were '''any''' keys - whether they matched the name or not!
 
  
==enableTimer==
+
==deleteStopWatch==
;enableTimer(name)
+
;deleteStopWatch(watchID/watchName)
:Enables or activates a timer that was previously disabled.  
+
 
 +
: This function removes an existing stopwatch, whether it only exists for this session or is set to be otherwise saved between sessions by using [[Manual:Lua_Functions#setStopWatchPersistence|setStopWatchPersistence()]] with a ''true'' argument.
  
 
;Parameters
 
;Parameters
* ''name:''
+
* ''watchID'' (number) / ''watchName'' (string): The stopwatch ID you get with [[Manual:Lua_Functions#createStopWatch|createStopWatch()]] or the name given to that function or later set with [[Manual:Lua_Functions#setStopWatchName|setStopWatchName()]].
: Expects the timer ID that was returned by [[Manual:Lua_Functions#tempTimer|tempTimer]] on creation of the timer or the name of the timer in case of a GUI timer.
+
 
<syntaxhighlight lang="lua">
+
;Returns:
-- enable the timer called 'my timer' that you created in Mudlets timers section
+
* ''true'' if the stopwatch was found and thus deleted, or ''nil'' and an error message if not - obviously using it twice with the same argument will fail the second time unless another one with the same name or ID was recreated before the second use.  Note that an empty string as a name ''will'' find the lowest ID numbered ''unnamed'' stopwatch and that will then find the next lowest ID number of unnamed ones until there are none left, if used repetitively!
enableTimer("my timer")
 
</syntaxhighlight>
 
  
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- or disable & enable a tempTimer you've made
+
lua MyStopWatch = createStopWatch("stopwatch_mine")
timerID = tempTimer(10, [[echo("hi!")]])
+
true
  
-- it won't go off now
+
lua display(MyStopWatch)
disableTimer(timerID)
+
4
-- it will continue going off again
 
enableTimer(timerID)
 
</syntaxhighlight>
 
  
==enableTrigger==
+
lua deleteStopWatch(MyStopWatch)
;enableTrigger(name)
+
true
:Enables or activates a trigger that was previously disabled.
 
  
;Parameters
+
lua deleteStopWatch(MyStopWatch)
* ''name:''
+
nil
: Expects the trigger ID that was returned by [[Manual:Lua_Functions#tempTrigger|tempTrigger]] or by any other temp*Trigger variants, or the name of the trigger in case of a GUI trigger.
 
<syntaxhighlight lang="lua">
 
-- enable the trigger called 'my trigger' that you created in Mudlets triggers section
 
enableTrigger("my trigger")
 
</syntaxhighlight>
 
  
<syntaxhighlight lang="lua">
+
"stopwatch with id 4 not found"
-- or disable & enable a tempTrigger you've made
 
triggerID = tempTrigger("some text that will match in a line", [[echo("hi!")]])
 
  
-- it won't go off now when a line with matching text comes by
+
lua deleteStopWatch("stopwatch_mine")
disableTrigger(triggerID)
+
nil
  
-- and now it will continue going off again
+
"stopwatch with name "stopwatch_mine" not found"
enableTrigger(triggerID)
+
</syntaxhighlight>
 +
 
 +
: See also: [[Manual:Lua_Functions#createStopWatch|createStopWatch()]],
 +
 
 +
{{MudletVersion|4.4}}
 +
 
 +
{{note}} Stopwatches that are not set to be persistent will be deleted automatically at the end of a session (or if [[Manual:Miscellaneous_Functions#resetProfile|resetProfile()]] is called).
 +
 
 +
==removeCmdLineSuggestion==
 +
;removeCmdLineSuggestion([name], suggestion)
 +
: Remove a suggestion for tab completion for specified command line.
 +
 
 +
: See also: [[Manual:Lua_Functions#addCmdLineSuggestion|addCmdLineSuggestion()]], [[Manual:Lua_Functions#clearCmdLineSuggestions|clearCmdLineSuggestions()]]
 +
 
 +
{{MudletVersion|4.11}}
 +
 
 +
;Parameters
 +
* ''name'': optional command line name, if skipped main command line will be used
 +
* ''suggestion'' - text to add to tab completion, non words characters at start and end of word should not be used (all characters except: `0-9A-Za-z_`)
 +
 
 +
Example:
 +
<syntaxhighlight lang="lua">
 +
removeCmdLineSuggestion("help")
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==exists==
+
==disableAlias==
;exists(name, type)
+
;disableAlias(name)
:Tells you how many things of the given type exist.  
+
:Disables/deactivates the alias by its name. If several aliases have this name, they'll all be disabled. If you disable an alias group, all the aliases inside the group will be disabled as well.
  
{{note}} This function is only for objects created in the script editor or via perm* functions. You don't need it for temp* functions and will not work for them.
+
: See also: [[#enableAlias|enableAlias()]], [[#disableTrigger|disableTrigger()]], [[#disableTimer|disableTimer()]], [[#disableKey|disableKey()]], [[#disableScript|disableScript()]].
  
 
;Parameters
 
;Parameters
 
* ''name:''
 
* ''name:''
: The name or the id returned by the temp* function to identify the item.
+
: The name of the alias. Passed as a string.
* ''type:''
 
: The type can be 'alias', 'trigger', 'timer', 'keybind' (Mudlet 3.2+), or 'script' (Mudlet 3.17+).
 
  
;Example
+
;Examples
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
echo("I have " .. exists("my trigger", "trigger") .. " triggers called 'my trigger'!")
+
--Disables the alias called 'my alias'
 +
disableAlias("my alias")
 
</syntaxhighlight>
 
</syntaxhighlight>
  
: You can also use this alias to avoid creating duplicate things, for example:
+
==disableKey==
<syntaxhighlight lang="lua">
+
;disableKey(name)
-- this code doesn't check if an alias already exists and will keep creating new aliases
+
:Disables key a key (macro) or a key group. When you disable a key group, all keys within the group will be implicitly disabled as well.
permAlias("Attack", "General", "^aa$", [[send ("kick rat")]])
+
 
 +
: See also: [[#enableKey|enableKey()]]
 +
 
 +
;Parameters
 +
* ''name:''
 +
: The name of the key or group to identify what you'd like to disable.
  
-- while this code will make sure that such an alias doesn't exist first
+
;Examples
-- we do == 0 instead of 'not exists' because 0 is considered true in Lua
 
if exists("Attack", "alias") == 0 then
 
    permAlias("Attack", "General", "^aa$", [[send ("kick rat")]])
 
end
 
</syntaxhighlight>
 
  
: Especially helpful when working with [[Manual:Lua_Functions#permTimer|permTimer]]:
 
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
if not exists("My animation timer", "timer") then
+
-- you could set multiple keys on the F1 key and swap their use as you wish by disabling and enabling them
  vdragtimer = permTimer("My animation timer", "", .016, onVDragTimer) -- 60fps timer!
+
disableKey("attack macro")
end
+
disableKey("jump macro")
+
enableKey("greet macro")
enableTimer("My animation timer")
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==getButtonState==
+
==disableScript==
;getButtonState()
+
;disableScript(name)
:This function can be used within checkbox button scripts (2-state buttons) to determine the current state of the checkbox.
+
:Disables a script that was previously enabled. Note that disabling a script only stops it from running in the future - it won't "undo" anything the script has made, such as labels on the screen.
 +
 
 +
: See also: [[#permScript|permScript()]], [[#appendScript|appendScript()]], [[#enableScript|enableScript()]], [[#getScript|getScript()]], [[#setScript|setScript()]]
  
:Returns ''2'' if button is checked, and ''1'' if it's not.
+
;Parameters
 +
* ''name'': name of the script.
  
 
;Example
 
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
local checked = getButtonState()
+
--Disables the script called 'my script'
if checked == 1 then
+
disableScript("my script")
    hideExits()
 
else
 
    showExits()
 
end
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==getCmdLine==
+
{{MudletVersion|4.8}}
;getCmdLine()
+
 
: Returns the current content of the main input line.
+
==disableTimer==
 +
;disableTimer(name)
 +
:Disables a timer from running it’s script when it fires - so the timer cycles will still be happening, just no action on them. If you’d like to permanently delete it, use [[Manual:Lua_Functions#killTrigger|killTrigger]] instead.
 +
 
 +
: See also: [[#enableTimer|enableTimer()]], [[#disableTrigger|disableTrigger()]], [[#disableAlias|disableAlias()]], [[#disableKey|disableKey()]], [[#disableScript|disableScript()]].
  
: See also: [[Manual:Lua_Functions#printCmdLine|printCmdLine()]]
+
;Parameters
 +
* ''name:''
 +
: Expects the timer ID that was returned by [[Manual:Lua_Functions#tempTimer|tempTimer]] on creation of the timer or the name of the timer in case of a GUI timer.
  
 
;Example
 
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- replaces whatever is currently in the input line by "55 backpacks"
+
--Disables the timer called 'my timer'
printCmdLine("55 backpacks")
+
disableTimer("my timer")
 
 
--prints the text "55 backpacks" to the main console
 
echo(getCmdLine())
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
{{note}} Available in Mudlet 3.1+
+
==disableTrigger==
 +
;disableTrigger(name)
 +
:Disables a permanent (one in the trigger editor) or a temporary trigger. When you disable a group, all triggers inside the group are disabled as well
  
==getStopWatches==
+
: See also: [[#enableTrigger|enableTrigger()]], [[#disableAlias|disableAlias()]], [[#disableTimer|disableTimer()]], [[#disableKey|disableKey()]], [[#disableScript|disableScript()]].
;table = getStopWatches()
 
  
: Returns a table of the details for each stopwatch in existence, the keys are the watch IDs but since there can be gaps in the ID number allocated for the stopwatches it will be necessary to use the ''pairs(...)'' rather than the ''ipairs(...)'' method to iterate through all of them in ''for'' loops!
+
;Parameters
: Each stopwatch's details will list the following items: ''name'' (string), ''isRunning'' (boolean), ''isPersistent'' (boolean), ''elapsedTime'' (table).  The last of these contains the same data as is returned by the results table from the [[Manual:Lua_Functions#getStopWatchBrokenDownTime|getStopWatchBrokenDownTime()]] function - namely ''days'' (positive integer), ''hours'' (integer, 0 to 23), ''minutes'' (integer, 0 to 59), ''second'' (integer, 0 to 59), ''milliSeconds'' (integer, 0 to 999), ''negative'' (boolean) with an additional ''decimalSeconds'' (number of seconds, with a decimal portion for the milli-seconds and possibly a negative sign, representing the whole elapsed time recorded on the stopwatch) - as would also be returned by the [[Manual:Lua_Functions#getStopWatchTime|getStopWatchTime()]] function.
+
* ''name:''
 +
: Expects the trigger ID that was returned by [[Manual:Lua_Functions#tempTrigger|tempTrigger]] or other temp*Trigger variants, or the name of the trigger in case of a GUI trigger.
  
 
;Example
 
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- on the command line:
+
-- Disables the trigger called 'my trigger'
lua getStopWatches()
+
disableTrigger("my trigger")
-- could return something like:
+
</syntaxhighlight>
{
+
 
  {
+
==enableAlias==
    isPersistent = true,
+
;enableAlias(name)
    elapsedTime = {
+
:Enables/activates the alias by it’s name. If several aliases have this name, they’ll all be enabled.
      minutes = 15,
+
 
      seconds = 2,
+
: See also: [[#disableAlias|disableAlias()]]
      negative = false,
+
 
      milliSeconds = 66,
+
;Parameters
      hours = 0,
+
* ''name:''
      days = 18,
+
: Expects the alias ID that was returned by [[Manual:Lua_Functions#tempAlias|tempAlias]] on creation of the alias or the name of the alias in case of a GUI alias.
      decimalSeconds = 1556102.066
+
 
    },
+
;Example
    name = "Playing time",
+
<syntaxhighlight lang="lua">
    isRunning = true
+
--Enables the alias called 'my alias'
  },
+
enableAlias("my alias")
  {
+
</syntaxhighlight>
    isPersistent = true,
+
 
    elapsedTime = {
+
==enableKey==
      minutes = 47,
+
;enableKey(name)
      seconds = 1,
+
:Enables a key (macro) or a group of keys (and thus all keys within it that aren't explicitly deactivated).
      negative = true,
+
 
      milliSeconds = 657,
+
;Parameters
      hours = 23,
+
* ''name:''
      days = 2,
+
: The name of the group that identifies the key.
      decimalSeconds = -258421.657
+
 
    },
+
<syntaxhighlight lang="lua">
    name = "TMC Vote",
+
-- you could use this to disable one key set for the numpad and activate another
    isRunning = true
+
disableKey("fighting keys")
  },
+
enableKey("walking keys")
  {
+
</syntaxhighlight>
    isPersistent = false,
+
{{note}} From Version '''3.10'' returns ''true'' if one or more keys or groups of keys were found that matched the name given or ''false'' if not; prior to then it returns ''true'' if there were '''any''' keys - whether they matched the name or not!
    elapsedTime = {
+
 
      minutes = 26,
+
==enableScript==
      seconds = 36,
+
;enableScript(name)
      negative = false,
+
:Enables / activates a script that was previously disabled.  
      milliSeconds = 899,
+
 
      hours = 3,
+
: See also: [[#permScript|permScript()]], [[#appendScript|appendScript()]], [[#disableScript|disableScript()]], [[#getScript|getScript()]], [[#setScript|setScript()]]
      days = 0,
+
 
      decimalSeconds = 12396.899
+
;Parameters
    },
+
* ''name'': name of the script.
    name = "",
+
<syntaxhighlight lang="lua">
    isRunning = false
+
-- enable the script called 'my script' that you created in Mudlet's script section
  },
+
enableScript("my script")
  [5] = {
+
</syntaxhighlight>
    isPersistent = false,
+
 
    elapsedTime = {
+
{{MudletVersion|4.8}}
      minutes = 0,
+
 
      seconds = 38,
+
==enableTimer==
      negative = false,
+
;enableTimer(name)
      milliSeconds = 763,
+
:Enables or activates a timer that was previously disabled.  
      hours = 0,
+
 
      days = 0,
+
;Parameters
      decimalSeconds = 38.763
+
* ''name:''
    },
+
: Expects the timer ID that was returned by [[Manual:Lua_Functions#tempTimer|tempTimer]] on creation of the timer or the name of the timer in case of a GUI timer.
    name = "",
+
<syntaxhighlight lang="lua">
    isRunning = true
+
-- enable the timer called 'my timer' that you created in Mudlets timers section
  }
+
enableTimer("my timer")
}
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
{{note}} Available from TBA.
+
<syntaxhighlight lang="lua">
 +
-- or disable & enable a tempTimer you've made
 +
timerID = tempTimer(10, [[echo("hi!")]])
  
==getStopWatchTime==
+
-- it won't go off now
;time = getStopWatchTime(watchID [or watchName from TBA])
+
disableTimer(timerID)
: Returns the time as a decimal number of seconds with up to three decimal places to give a milli-seconds (thousandths of a second) resolution.
+
-- it will continue going off again
: Please note that, prior to TBA it was not possible to retrieve the elapsed time after the stopwatch had been stopped, retrieving the time was not possible as the returned value then was an indeterminate, meaningless time; after the TBA release, however, the elapsed value can be retrieved at any time, even if the stopwatch has not been started since creation or modified with the [[Manual:Lua_Functions#adjustStopWatch|adjustStopWatch()]] function introduced in that release.
+
enableTimer(timerID)
 +
</syntaxhighlight>
  
: See also: [[Manual:Lua_Functions#createStopWatch|createStopWatch()]], [[Manual:Lua_Functions#startStopWatch|startStopWatch()]], [[Manual:Lua_Functions#stopStopWatch|stopStopWatch()]], and, from TBA: [[Manual:Lua_Functions#destroyStopWatch|destroyStopWatch()]], [[Manual:Lua_Functions#getStopWatch es|getStopWatches()]], [[Manual:Lua_Functions#getStopWatchBrokenDownTime|getStopWatchBrokenDownTime()]].
+
==enableTrigger==
 
+
;enableTrigger(name)
:Returns a number
+
:Enables or activates a trigger that was previously disabled.
  
 
;Parameters
 
;Parameters
* ''watchID''
+
* ''name:''
: The ID number of the watch.
+
: Expects the trigger ID that was returned by [[Manual:Lua_Functions#tempTrigger|tempTrigger]] or by any other temp*Trigger variants, or the name of the trigger in case of a GUI trigger.
 +
<syntaxhighlight lang="lua">
 +
-- enable the trigger called 'my trigger' that you created in Mudlets triggers section
 +
enableTrigger("my trigger")
 +
</syntaxhighlight>
  
;Example
 
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- an example of showing the time left on the stopwatch
+
-- or disable & enable a tempTrigger you've made
teststopwatch = teststopwatch or createStopWatch()
+
triggerID = tempTrigger("some text that will match in a line", [[echo("hi!")]])
startStopWatch(teststopwatch)
+
 
echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))
+
-- it won't go off now when a line with matching text comes by
tempTimer(1, [[echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))]])
+
disableTrigger(triggerID)
tempTimer(2, [[echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))]])
+
 
stopStopWatch(teststopwatch)
+
-- and now it will continue going off again
 +
enableTrigger(triggerID)
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==getStopWatchBrokenDownTime==
+
==exists==
; brokenDownTimeTable = getStopWatchBrokenDownTime(watchID or watchName)
+
;exists(name/IDnumber, type)
: Returns the current stopwatch time, whether the stopwatch is running or is stopped, as a table, broken down into:
+
:Returns the number of things with the given name or number of the given type - and 0 if none are present. Beware that all numbers are true in Lua, including zero.
* "days" (integer)
 
* "hours" (integer, 0 to 23)
 
* "minutes" (integer, 0 to 59)
 
* "seconds" (integer, 0 to 59)
 
* "milliSeconds" (integer, 0 to 999)
 
* "negative" (boolean, true if value is less than zero)
 
  
{{note}} This is only a proposal - not available in Mudlet yet.
+
;Parameters
 +
* ''name:''
 +
: The name (as a string) or, from '''Mudlet 4.17.0''', the ID number of a single item, (which will be that returned by a ''temp*'' or ''perm*'' function to create such an item to identify the item).
 +
* ''type:''
 +
: The type can be 'alias', 'button' (Mudlet 4.10+), 'trigger', 'timer', 'keybind' (Mudlet 3.2+), or 'script' (Mudlet 3.17+).
  
: See also: [[Manual:Lua_Functions#startStopWatch|startStopWatch()]], [[Manual:Lua_Functions#stopStopWatch|stopStopWatch()]], and, from TBA: [[Manual:Lua_Functions#destroyStopWatch|destroyStopWatch()]], [[Manual:Lua_Functions#getStopWatch es|getStopWatches()]], [[Manual:Lua_Functions#getStopWatchTime|getStopWatchTime()]].
+
:See also: [[#isActive|isActive(...)]]
  
;Parameters
+
;Example
* ''watchID'' / ''watchName''
+
<syntaxhighlight lang="lua">
: The ID number or the name of the watch.
+
echo("I have " .. exists("my trigger", "trigger") .. " triggers called 'my trigger'!")
 +
</syntaxhighlight>
  
;Example
+
: You can also use this alias to avoid creating duplicate things, for example:
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
--an example, showing the presetting of a stopwatch.
+
-- this code doesn't check if an alias already exists and will keep creating new aliases
 +
permAlias("Attack", "General", "^aa$", [[send ("kick rat")]])
 +
 
 +
-- while this code will make sure that such an alias doesn't exist first
 +
-- we do == 0 instead of 'not exists' because 0 is considered true in Lua
 +
if exists("Attack", "alias") == 0 then
 +
    permAlias("Attack", "General", "^aa$", [[send ("kick rat")]])
 +
end
 +
</syntaxhighlight>
  
--This will fail if the stopwatch with the given name
+
: Especially helpful when working with [[Manual:Lua_Functions#permTimer|permTimer]]:
-- already exists, but then we can use the existing one:
+
<syntaxhighlight lang="lua">
local watchId = createStopWatch("TopMudSiteVoteStopWatch")
+
if not exists("My animation timer", "timer") then
if watchId ~= nil then
+
   vdragtimer = permTimer("My animation timer", "", .016, onVDragTimer) -- 60fps timer!
  -- so we have just created the stopwatch, we want it
+
end
  -- to be saved for future sessions:
+
  setStopWatchPersistence("TopMudSiteVoteStopWatch", true)
+
enableTimer("My animation timer")
   -- and set it to count down the 12 hours until we can
+
</syntaxhighlight>
  -- revote:
 
  adjustStopWatch("TopMudSiteVoteStopWatch", -60*60*12)
 
  -- and start it running
 
  startStopWatch("TopMudSiteVoteStopWatch")
 
  
  openWebPage("http://www.topmudsites.com/vote-wotmud.html")
+
{{Note}} A positive ID number will return either a ''1'' or ''0'' value and not a lua boolean ''true'' or ''false'' as might otherwise be expected, this is for constancy with the way the function behaves for a name.
end
 
  
--[[ now I can check when it is time to vote again, even when
+
==getButtonState==
I stop the session and restart later by running the following
+
;getButtonState([ButtonNameOrID])
from a perm timer - perhaps on a 15 minute interval. Note that
+
:This function can be used within checkbox button scripts (2-state buttons) to determine the current state of the checkbox.
when loaded in a new session the Id it gets is unlikely to be
 
the same as that when it was created - but that is not a
 
problem as the name is preserved and, if the timer is running
 
when the profile is saved at the end of the session then the
 
elapsed time will continue to increase to reflect the real-life
 
passage of time:]]
 
  
local voteTimeTable = getStopWatchBrokenDownTime("TopMudSiteVoteStopWatch")
+
: See also: [[#setButtonState|setButtonState()]].
 +
{{note}} Function can be used in any Mudlet script outside of a button's own script with parameter ButtonNameOrID available from Mudlet version 4.13.0+
  
if voteTimeTable["negative"] then
+
;Parameters
  if voteTimeTable["hours"] == 0 and voteTimeTable["minutes"] < 30 then
+
* ''ButtonNameOrID:''
     echo("Voting for WotMUD on Top Mud Site in " .. voteTimeTable["minutes"] .. " minutes...")
+
: a numerical ID or string name to identify the checkbox button.
  end
+
 
 +
;Returns
 +
* ''2'' if the button has "checked" state, or ''1'' if the button is not checked. (or a ''nil'' and an error message if ButtonNameOrID did not identify a check-able button)
 +
 
 +
;Example
 +
<syntaxhighlight lang="lua">
 +
-- check from within the script of a check-able button:
 +
local checked = getButtonState()
 +
if checked == 1 then
 +
    hideExits()
 +
else
 +
    showExits()
 +
end
 +
</syntaxhighlight>
 +
 
 +
<syntaxhighlight lang="lua">
 +
-- check from anywhere in another Lua script of the same profile (available from Mudlet 4.13.0)
 +
local checked, errMsg = getButtonState("Sleep")
 +
if checked then
 +
     shouldBeMounted = shouldBeMounted or false
 +
    sendAll("wake", "stand")
 +
    if shouldBeMounted then
 +
        send("mount horse")
 +
    end
 
else
 
else
  echo("Oooh, it is " .. voteTimeTable["days"] .. " days, " .. voteTimeTable["hours"] .. " hours and " .. voteTimeTable["minutes"] .. " minutes past the time to Vote on Top Mud Site - doing it now!")
+
    -- Global used to record if we were on a horse before our nap:
  openWebPage("http://www.topmudsites.com/vote-wotmud.html")
+
    shouldBeMounted = mounted or false
  resetStopWatch("TopMudSiteVoteStopWatch")
+
    if shouldBeMounted then
  adjustStopWatch(watchId, -60*60*12)
+
        send("dismount")
 +
    end
 +
    sendAll("sit", "sleep")
 
end
 
end
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==invokeFileDialog==
+
==getCmdLine==
;invokeFileDialog(fileOrFolder, dialogTitle)
+
;getCmdLine([name])
: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.
+
: Returns the current content of the given command line.
 +
: See also: [[Manual:Lua_Functions#printCmdLine|printCmdLine()]]
 +
 
 +
{{MudletVersion|3.1}}
  
 
;Parameters
 
;Parameters
* ''fileOrFolder:'' ''true'' for file selection, ''false'' for folder selection.
+
* ''name'': (optional) name of the command line. If not given, it returns the text of the main commandline.
* ''dialogTitle'': what to say in the window title.
 
  
;Examples
+
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
function whereisit()
+
-- replaces whatever is currently in the input line by "55 backpacks"
  local path = invokeFileDialog(false, "Where should we save the file? Select a folder and click Open")
+
printCmdLine("55 backpacks")
  
  if path == "" then return nil else return path end
+
--prints the text "55 backpacks" to the main console
end
+
echo(getCmdLine())
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==isActive==
+
==getConsoleBufferSize==
;isActive(name, type)
+
;local lineLimit, sizeOfBatchDeletion = getConsoleBufferSize([consoleName])
:You can use this function to check if something, or somethings, are active.
+
:Returns, on success, the maximum number of lines a buffer (main window or a miniconsole) can hold and how many will be removed at a time when that limit is exceeded; returns a ''nil'' and an error message on failure.
:Returns the number of active things - and 0 if none are active. Beware that all numbers are true in Lua, including zero.
+
: See also: [[Manual:Mudlet_Object_Functions#setConsoleBufferSize|setConsoleBufferSize()]]
  
 
;Parameters
 
;Parameters
* ''name:''
+
* ''consoleName:''
: The name or the id returned by temp* function to identify the item.
+
: (optional) The name of the window. If omitted, uses the main console.
* ''type:''
 
: The type can be 'alias', 'trigger', 'timer', 'keybind' (Mudlet 3.2+), or 'script' (Mudlet 3.17+).
 
 
 
 
;Example
 
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
echo("I have " .. isActive("my trigger", "trigger") .. " currently active trigger(s) called 'my trigger'!")
+
-- sets the main window's size and how many lines will be deleted
 +
-- when it gets to that size to be as small as possible:
 +
setConsoleBufferSize("main", 1, 1)
 +
true
 +
 
 +
-- find out what the numbers are:
 +
local lineLimit, sizeOfBatchDeletion = getConsoleBufferSize()
 +
echo("\nWhen the main console gets to " .. lineLimit .. " lines long, the first " .. sizeOfBatchDeletion .. " lines will be removed.\n")
 +
When the main console gets to 100 lines long, the first 1 lines will be removed.
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==isPrompt==
+
{{MudletVersion|4.17}}
;isPrompt()
+
 
:Returns true or false depending on if the line at the cursor position 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).
+
==getNamedTimers==
 +
; timers = getNamedTimers(userName)
  
:Example use could be as a Lua function, making closing gates on a prompt real easy.
+
:Returns a list of all the named timers' names as a table.
  
;Example
+
;See also: [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]]
<syntaxhighlight lang="lua">
 
-- make a trigger pattern with 'Lua function', and this will trigger on every prompt!
 
return isPrompt()
 
</syntaxhighlight>
 
  
==killAlias==
+
{{MudletVersion|4.14}}
;killAlias(aliasID)
 
:Deletes a temporary alias with the given ID.
 
  
 
;Parameters
 
;Parameters
* ''aliasID:''
+
* ''userName:''
: The id returned by [[Manual:Lua_Functions#tempAlias|tempAlias]] to identify the alias.
+
: The user name the event handler was registered under.
 +
 
 +
;Returns
 +
* a table of handler names. { "DemonVitals", "DemonInv" } for example. {} if none are registered
  
 +
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- deletes the alias with ID 5
+
  local timers = getNamedTimers("Demonnic")
killAlias(5)
+
  display(timers)
 +
  -- {}
 +
  registerNamedTimer("Test1", "testEvent", "testFunction")
 +
  registerNamedTimer("Test2", "someOtherEvent", myHandlerFunction)
 +
  timers = getNamedTimers("Demonnic")
 +
  display(timers)
 +
  -- { "Test1", "Test2" }
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==killKey==
+
== getProfileStats==
;killKey(name)
+
;getProfileStats()
:Deletes a keybinding with the given name. If several keybindings have this name, they'll all be deleted.
 
  
;Parameters
+
:Returns a table with profile statistics for how many triggers, patterns within them, aliases, keys, timers, and scripts the profile has. Similar to the Statistics button in the script editor, accessible to Lua scripting.
* ''name:''
 
: The name or the id returned by [[Manual:Lua_Functions#tempKey|tempKey]] to identify the key.
 
  
{{note}} Available in Mudlet 3.2+
+
{{MudletVersion|4.15}}
  
 +
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- make a temp key
+
-- show all stats
local keyid = tempKey(mudlet.key.F8, [[echo("hi!")]])
+
display(getProfileStats())
 +
 
 +
-- check how many active triggers there are
 +
activetriggers = getProfileStats().triggers.active
 +
cecho(f"<PaleGreen>We have <SlateGrey>{activetriggers}<PaleGreen> active triggers!\n")
  
-- delete the said temp key
+
-- triggers can have many patterns, so let's check that as well
killKey(keyid)
+
patterns = getProfileStats().triggers.patterns.active
 +
triggers = getProfileStats().triggers.active
 +
cecho(f"<PaleGreen>We have <SlateGrey>{patterns}<PaleGreen> active patterns within <SlateGrey>{triggers}<PaleGreen> triggers!\n")
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==killTimer==
+
==getStopWatches==
;killTimer(id)
+
;table = getStopWatches()
:Deletes a [[Manual:Lua_Functions#tempTimer|tempTimer]].
 
  
{{note}} Non-temporary timers that you have set up in the GUI or by using [[#permTimer|permTimer]] cannot be deleted with this function. Use [[Manual:Lua_Functions#disableTimer|disableTimer()]] and [[Manual:Lua_Functions#enableTimer|enableTimer()]] to turn them on or off.
+
: Returns a table of the details for each stopwatch in existence, the keys are the watch IDs but since there can be gaps in the ID number allocated for the stopwatches it will be necessary to use the ''pairs(...)'' rather than the ''ipairs(...)'' method to iterate through all of them in ''for'' loops!
 
+
: Each stopwatch's details will list the following items: ''name'' (string), ''isRunning'' (boolean), ''isPersistent'' (boolean), ''elapsedTime'' (table).  The last of these contains the same data as is returned by the results table from the [[Manual:Lua_Functions#getStopWatchBrokenDownTime|getStopWatchBrokenDownTime()]] function - namely ''days'' (positive integer), ''hours'' (integer, 0 to 23), ''minutes'' (integer, 0 to 59), ''second'' (integer, 0 to 59), ''milliSeconds'' (integer, 0 to 999), ''negative'' (boolean) with an additional ''decimalSeconds'' (number of seconds, with a decimal portion for the milli-seconds and possibly a negative sign, representing the whole elapsed time recorded on the stopwatch) - as would also be returned by the [[Manual:Lua_Functions#getStopWatchTime|getStopWatchTime()]] function.
;Parameters
 
* ''id:'' the ID returned by [[Manual:Lua_Functions#tempTimer|tempTimer]].
 
 
 
: Returns true on success and false if the timer id doesn’t exist anymore (timer has already fired) or the timer is not a temp timer.
 
  
 
;Example
 
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- create the timer and remember the timer ID
+
-- on the command line:
timerID = tempTimer(10, [[echo("hello!")]])
+
lua getStopWatches()
 
+
-- could return something like:
-- delete the timer
+
{
if killTimer(timerID) then echo("deleted the timer") else echo("timer is already deleted") end
+
  {
</syntaxhighlight>
+
    isPersistent = true,
 
+
    elapsedTime = {
==killTrigger==
+
      minutes = 15,
;killTrigger(id)
+
      seconds = 2,
:Deletes a [[Manual:Lua_Functions#tempTimer|tempTrigger]], or a trigger made with one of the ''temp<type>Trigger()'' functions.
+
      negative = false,
 
+
      milliSeconds = 66,
{{note}} When used in out of trigger contexts, the triggers are disabled and deleted upon the next line received from the game - so if you are testing trigger deletion within an alias, the 'statistics' window will be reporting trigger counts that are disabled and pending removal, and thus are no cause for concern.
+
      hours = 0,
 
+
      days = 18,
;Parameters
+
      decimalSeconds = 1556102.066
* ''id:''
+
    },
: The ID returned by [[Manual:Lua_Functions#tempTimer|tempTimer]] to identify the item. ID is a string and not a number.
+
    name = "Playing time",
 
+
    isRunning = true
:Returns true on success and false if the trigger id doesn’t exist anymore (trigger has already fired) or the trigger is not a temp trigger.
+
  },
 
+
  {
==permAlias==
+
    isPersistent = true,
;permAlias(name, parent, regex, lua code)
+
    elapsedTime = {
 
+
      minutes = 47,
:Creates a persistent alias that stays after Mudlet is restarted and shows up in the Script Editor.
+
      seconds = 1,
 
+
      negative = true,
;Parameters
+
      milliSeconds = 657,
* ''name:''
+
      hours = 23,
: The name you’d like the alias to have.
+
      days = 2,
* ''parent:''
+
      decimalSeconds = -258421.657
: The name of the group, or another alias you want the trigger to go in - however if such a group/alias doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
+
    },
* ''regex:''
+
    name = "TMC Vote",
: The pattern that you’d like the alias to use.
+
    isRunning = true
* ''lua code:''
+
  },
: The script the alias will do when it matches.
+
  {
;Example
+
    isPersistent = false,
<syntaxhighlight lang="lua">
+
    elapsedTime = {
-- creates an alias called "new alias" in a group called "my group"
+
      minutes = 26,
permAlias("new alias", "my group", "^test$", [[echo ("say it works! This alias will show up in the script editor too.")]])
+
      seconds = 36,
</syntaxhighlight>
+
      negative = false,
 
+
      milliSeconds = 899,
{{note}} Mudlet by design allows duplicate names - so calling permAlias with the same name will keep creating new aliases. You can check if an alias already exists with the [[Manual:Lua_Functions#exists|exists]] function.
+
      hours = 3,
 
+
      days = 0,
==permGroup==
+
      decimalSeconds = 12396.899
;permGroup(name, itemtype, [parent])
+
    },
 
+
    name = "",
: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.
+
    isRunning = false
;Parameters
+
  },
* ''name:''
+
  [5] = {
: The name of the new group item you want to create.
+
    isPersistent = false,
* ''itemtype:''
+
    elapsedTime = {
: The type of the item, can be trigger, alias, or timer.
+
      minutes = 0,
* ''parent:''
+
      seconds = 38,
: (optional) Name of existing item which the new item will be created as a child of.
+
      negative = false,
 
+
      milliSeconds = 763,
;Example
+
      hours = 0,
<syntaxhighlight lang="lua">
+
      days = 0,
--create a new trigger group
+
      decimalSeconds = 38.763
permGroup("Combat triggers", "trigger")
+
    },
 
+
    name = "",
--create a new alias group only if one doesn't exist already
+
    isRunning = true
if exists("Defensive aliases", "alias") == 0 then
+
   }
   permGroup("Defensive aliases", "alias")
+
}
end
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
{{Note}} Added to Mudlet in the 2.0 final release. Parameter ''parent'' available in Mudlet 3.1+
+
{{MudletVersion|4.4}}
  
==permPromptTrigger==
+
==getStopWatchTime==
;permPromptTrigger(name, parent, lua code)
+
;time = getStopWatchTime(watchID [or watchName from Mudlet 4.4.0])
:Creates a persistent trigger for the in-game prompt that stays after Mudlet is restarted and shows up in the Script Editor.
+
: Returns the time as a decimal number of seconds with up to three decimal places to give a milli-seconds (thousandths of a second) resolution.
 +
: Please note that, prior to 4.4.0 it was not possible to retrieve the elapsed time after the stopwatch had been stopped, retrieving the time was not possible as the returned value then was an indeterminate, meaningless time; from the 4.4.0 release, however, the elapsed value can be retrieved at any time, even if the stopwatch has not been started since creation or modified with the [[Manual:Lua_Functions#adjustStopWatch|adjustStopWatch()]] function introduced in that release.
 +
 
 +
: See also: [[Manual:Lua_Functions#createStopWatch|createStopWatch()]], [[Manual:Lua_Functions#startStopWatch|startStopWatch()]], [[Manual:Lua_Functions#stopStopWatch|stopStopWatch()]], [[Manual:Lua_Functions#deleteStopWatch|deleteStopWatch()]], [[Manual:Lua_Functions#getStopWatch es|getStopWatches()]], [[Manual:Lua_Functions#getStopWatchBrokenDownTime|getStopWatchBrokenDownTime()]].
  
{{note}} If the trigger is not working, check that the '''N:''' bottom-right has a number. This feature requires telnet Go-Ahead (GA) or End-of-Record (EOR) to be enabled in your game. Available in Mudlet 3.6+
+
:Returns a number
  
;Parameters:
+
;Parameters
* ''name'' is the name you’d like the trigger to have.
+
* ''watchID''
* ''parent'' is the name of the group, or another trigger you want the trigger to go in - however if such a group/trigger doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
+
: The ID number of the watch.
* ''lua code'' is the script the trigger will do when it matches.
 
  
;Example:
+
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
permPromptTrigger("echo on prompt", "", [[echo("hey! this thing is working!\n")]])
+
-- an example of showing the time left on the stopwatch
 +
teststopwatch = teststopwatch or createStopWatch()
 +
startStopWatch(teststopwatch)
 +
echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))
 +
tempTimer(1, [[echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))]])
 +
tempTimer(2, [[echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))]])
 +
stopStopWatch(teststopwatch)
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
+
==getStopWatchBrokenDownTime==
==permRegexTrigger==
+
; brokenDownTimeTable = getStopWatchBrokenDownTime(watchID or watchName)
;permRegexTrigger(name, parent, pattern table, lua code)
+
: Returns the current stopwatch time, whether the stopwatch is running or is stopped, as a table, broken down into:
:Creates a persistent trigger with one or more ''regex'' patterns that stays after Mudlet is restarted and shows up in the Script Editor.
+
* "days" (integer)
 +
* "hours" (integer, 0 to 23)
 +
* "minutes" (integer, 0 to 59)
 +
* "seconds" (integer, 0 to 59)
 +
* "milliSeconds" (integer, 0 to 999)
 +
* "negative" (boolean, true if value is less than zero)
 +
 
 +
: See also: [[Manual:Lua_Functions#startStopWatch|startStopWatch()]], [[Manual:Lua_Functions#stopStopWatch|stopStopWatch()]], [[Manual:Lua_Functions#deleteStopWatch|deleteStopWatch()]], [[Manual:Lua_Functions#getStopWatch es|getStopWatches()]], [[Manual:Lua_Functions#getStopWatchTime|getStopWatchTime()]].
  
 
;Parameters
 
;Parameters
* ''name'' is the name you’d like the trigger to have.
+
* ''watchID'' / ''watchName''
* ''parent'' is the name of the group, or another trigger you want the trigger to go in - however if such a group/trigger doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
+
: The ID number or the name of the watch.
* ''pattern table'' is a table of patterns that you’d like the trigger to use - it can be one or many.
+
 
* ''lua code'' is the script the trigger will do when it matches.
 
 
;Example
 
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- Create a regex trigger that will match on the prompt to record your status
+
--an example, showing the presetting of a stopwatch.
permRegexTrigger("Prompt", "", {"^(\d+)h, (\d+)m"}, [[health = tonumber(matches[2]); mana = tonumber(matches[3])]])
 
</syntaxhighlight>
 
{{note}} Mudlet by design allows duplicate names - so calling permRegexTrigger with the same name will keep creating new triggers. You can check if a trigger already exists with the [[Manual:Lua_Functions#exists|exists()]] function.
 
  
==permBeginOfLineStringTrigger==
+
--This will fail if the stopwatch with the given name
;permBeginOfLineStringTrigger(name, parent, pattern table, lua code)
+
-- already exists, but then we can use the existing one:
:Creates a persistent trigger that stays after Mudlet is restarted and shows up in the Script Editor. The trigger will go off whenever one of the ''regex'' patterns it's provided with matches. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls.
+
local watchId = createStopWatch("TopMudSiteVoteStopWatch")
 +
if watchId ~= nil then
 +
  -- so we have just created the stopwatch, we want it
 +
  -- to be saved for future sessions:
 +
  setStopWatchPersistence("TopMudSiteVoteStopWatch", true)
 +
  -- and set it to count down the 12 hours until we can
 +
  -- revote:
 +
  adjustStopWatch("TopMudSiteVoteStopWatch", -60*60*12)
 +
  -- and start it running
 +
  startStopWatch("TopMudSiteVoteStopWatch")
  
;Parameters
+
  openWebPage("http://www.topmudsites.com/vote-wotmud.html")
* ''name'' is the name you’d like the trigger to have.
+
end
* ''parent'' is the name of the group, or another trigger you want the trigger to go in - however if such a group/trigger doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
 
* ''pattern table'' is a table of patterns that you’d like the trigger to use - it can be one or many.
 
* ''lua code'' is the script the trigger will do when it matches.
 
  
;Examples
+
--[[ now I can check when it is time to vote again, even when
<syntaxhighlight lang="lua">
+
I stop the session and restart later by running the following
-- Create a trigger that will match on anything that starts with "You sit" and do "stand".
+
from a perm timer - perhaps on a 15 minute interval. Note that
-- It will not go into any groups, so it'll be on the top.
+
when loaded in a new session the Id it gets is unlikely to be
permBeginOfLineStringTrigger("Stand up", "", {"You sit"}, [[send ("stand")]])
+
the same as that when it was created - but that is not a
 +
problem as the name is preserved and, if the timer is running
 +
when the profile is saved at the end of the session then the
 +
elapsed time will continue to increase to reflect the real-life
 +
passage of time:]]
 +
 
 +
local voteTimeTable = getStopWatchBrokenDownTime("TopMudSiteVoteStopWatch")
  
-- Another example - lets put our trigger into a "General" folder and give it several patterns.
+
if voteTimeTable["negative"] then
permBeginOfLineStringTrigger("Stand up", "General", {"You sit", "You fall", "You are knocked over by"}, [[send ("stand")]])
+
  if voteTimeTable["hours"] == 0 and voteTimeTable["minutes"] < 30 then
 +
    echo("Voting for WotMUD on Top Mud Site in " .. voteTimeTable["minutes"] .. " minutes...")
 +
  end
 +
else
 +
  echo("Oooh, it is " .. voteTimeTable["days"] .. " days, " .. voteTimeTable["hours"] .. " hours and " .. voteTimeTable["minutes"] .. " minutes past the time to Vote on Top Mud Site - doing it now!")
 +
  openWebPage("http://www.topmudsites.com/vote-wotmud.html")
 +
  resetStopWatch("TopMudSiteVoteStopWatch")
 +
  adjustStopWatch("TopMudSiteVoteStopWatch", -60*60*12)
 +
end
 
</syntaxhighlight>
 
</syntaxhighlight>
{{note}} Mudlet by design allows duplicate names - so calling permBeginOfLineStringTrigger with the same name will keep creating new triggers. You can check if a trigger already exists with the [[Manual:Lua_Functions#exists|exists()]] function.
 
  
==permSubstringTrigger==
+
{{MudletVersion|4.7}}
;permSubstringTrigger( name, parent, pattern table, lua code )
+
 
:Creates a persistent trigger with one or more ''substring'' patterns that stays after Mudlet is restarted and shows up in the Script Editor.
+
==getScript==
 +
; getScript(scriptName, [occurrence])
 +
: Returns the script with the given name. If you have more than one script with the same name, specify the occurrence to pick a different one. Returns -1 if the script doesn't exist.
 +
 
 +
: See also: [[Manual:Lua_Functions#permScript|permScript()]], [[Manual:Lua_Functions#enableScript|enableScript()]], [[Manual:Lua_Functions#disableScript|disableScript()]], [[Manual:Lua_Functions#setScript|setScript()]], [[Manual:Lua_Functions#appendScript|appendScript()]]
 +
 
 
;Parameters
 
;Parameters
* ''name'' is the name you’d like the trigger to have.
+
* ''scriptName'': name of the script.
* ''parent'' is the name of the group, or another trigger you want the trigger to go in - however if such a group/trigger doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
+
* ''occurrence'': (optional) occurence of the script in case you have many with the same name.
* ''pattern table'' is a table of patterns that you’d like the trigger to use - it can be one or many.
+
 
* ''lua code'' is the script the trigger will do when it matches.
 
 
;Example
 
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- Create a trigger to highlight the word "pixie" for us
+
-- show the "New script" on screen
permSubstringTrigger("Highlight stuff", "General", {"pixie"},
+
print(getScript("New script"))
[[selectString(line, 1) bg("yellow") resetFormat()]])
 
  
-- Or another trigger to highlight several different things
+
-- an example of returning the script Lua code from the second occurrence of "testscript"
permSubstringTrigger("Highlight stuff", "General", {"pixie", "cat", "dog", "rabbit"},
+
test_script_code = getScript("testscript", 2)
[[selectString(line, 1) fg ("blue") bg("yellow") resetFormat()]])
 
 
</syntaxhighlight>
 
</syntaxhighlight>
{{note}} Mudlet by design allows duplicate names - so calling permSubstringTrigger with the same name will keep creating new triggers. You can check if a trigger already exists with the [[Manual:Lua_Functions#exists|exists()]] function.
 
  
==permTimer==
+
{{MudletVersion|4.8}}
;permTimer(name, parent, seconds, lua code)
+
 
: Creates a persistent timer that stays after Mudlet is restarted and shows up in the Script Editor.
+
==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
 
;Parameters
* ''name''  
+
* ''fileOrFolder:'' ''true'' for file selection, ''false'' for folder selection.
:name of the timer.
+
* ''dialogTitle'': what to say in the window title.
* ''parent''  
+
 
:name of the timer group you want the timer to go in.
+
;Examples
* ''seconds''  
 
:a floating point number specifying a delay in seconds after which the timer will do the lua code (stored as the timer's "script") you give it as a string.
 
* ''lua code'' is the code with string you are doing this to.
 
 
 
;Returns
 
* a unique id number for that timer.
 
 
 
;Example:
 
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- create a timer in the "first timer group" group
+
function whereisit()
permTimer("my timer", "first timer group", 4.5, [[send ("my timer that's in my first timer group fired!")]])
+
  local path = invokeFileDialog(false, "Where should we save the file? Select a folder and click Open")
-- create a timer that's not in any group; just at the top
 
permTimer("my timer", "", 4.5, [[send ("my timer that's in my first timer group fired!")]])
 
  
-- enable timer - they start off disabled until you're ready
+
  if path == "" then return nil else return path end
enableTimer("my timer")
+
end
 
</syntaxhighlight>
 
</syntaxhighlight>
  
{{note}} The timer is NOT active after creation, it will need to be enabled by a call to [[#enableTimer|enableTimer()]] before it starts.
+
==isActive==
 +
;isActive(name/IDnumber, type)
 +
:You can use this function to check if something, or somethings, are active.
 +
:Returns the number of active things - and 0 if none are active. Beware that all numbers are true in Lua, including zero.
  
{{note}} Mudlet by design allows duplicate names - so calling permTimer with the same name will keep creating new timers. You can check if a timer already exists with the [[Manual:Lua_Functions#exists|exists()]] function.
+
;Parameters
 +
* ''name:''
 +
: The name (as a string) or, from '''Mudlet 4.17.0''', the ID number of a single item, (which will be that returned by a ''temp*'' function to create such an item to identify the item).
 +
* ''type:''
 +
: The type can be 'alias', 'button' (Mudlet 4.10+), 'trigger', 'timer', 'keybind' (Mudlet 3.2+), or 'script' (Mudlet 3.17+).
  
==permKey==
+
: See also: [[#exists|exists(...)]]
;permKey(name, parent, [modifier], key code, lua code)
 
: Creates a persistent key that stays after Mudlet is restarted and shows up in the Script Editor.
 
  
;Parameters
+
;Example
* ''name''
+
<syntaxhighlight lang="lua">
:name of the key.
+
echo("I have " .. isActive("my trigger", "trigger") .. " currently active trigger(s) called 'my trigger'!")
* ''parent''
 
:name of the timer group you want the timer to go in or "" for the top level.
 
* ''modifier''
 
:(optional) modifier to use - can be one of ''mudlet.keymodifier.Control'', ''mudlet.keymodifier.Alt'', ''mudlet.keymodifier.Shift'', ''mudlet.keymodifier.Meta'', ''mudlet.keymodifier.Keypad'', or ''mudlet.keymodifier.GroupSwitch'' or the default value of ''mudlet.keymodifier.None'' which is used if the argument is omitted. To use multiple modifiers, add them together: ''(mudlet.keymodifier.Shift + mudlet.keymodifier.Control)''
 
* ''key code''
 
: actual key to use - one of the values available in ''mudlet.key'', e.g. ''mudlet.key.Escape'', ''mudlet.key.Tab'', ''mudlet.key.F1'', ''mudlet.key.A'', and so on. The list is a bit long to list out in full so it is [https://github.com/Mudlet/Mudlet/blob/development/src/mudlet-lua/lua/KeyCodes.lua#L2 available here].
 
* ''lua code'
 
: code you would like the key to run.
 
  
;Returns
+
-- Can also be used to check if a specific item is enabled or not.
* a unique id number for that key.
+
if isActive("spellname", "trigger") > 0 then
 +
  -- the spellname trigger is active
 +
else
 +
  -- it is not active
 +
end
 +
</syntaxhighlight>
  
{{note}} Available in Mudlet 3.2+
+
{{note}} A positive ID number that does not exist will still return a ''0'' value, this is for constancy with the way the function behaves for a name that does not refer to any item either. If necessary the existence of an item should be confirmed with [[#exists|exists(...)]] first.
  
;Example:
+
==isPrompt==
<syntaxhighlight lang="lua">
+
;isPrompt()
-- create a key at the top level for F8
+
:Returns true or false depending on if the line at the cursor position is a prompt. This infallible feature is available for games 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).
permKey("my key", "", mudlet.key.F8, [[echo("hey this thing actually works!\n")]])
 
  
-- or Ctrl+F8
+
:Example use could be as a Lua function, making closing gates on a prompt real easy.
permKey("my key", "", mudlet.keymodifier.Control, mudlet.key.F8, [[echo("hey this thing actually works!\n")]])
 
  
-- Ctrl+Shift+W
+
;Example
permKey("jump keybinding", "", mudlet.keymodifier.Control + mudlet.keymodifier.Shift, mudlet.key.W, [[send("jump")]])
+
<syntaxhighlight lang="lua">
 +
-- make a trigger pattern with 'Lua function', and this will trigger on every prompt!
 +
-- note that this is deprecated as we now have the prompt trigger type which does the same thing
 +
-- the function can still be useful for detecting if you're running code on a prompt for other reasons
 +
-- but you should be using a prompt trigger for this rather than a Lua function trigger.
 +
return isPrompt()
 
</syntaxhighlight>
 
</syntaxhighlight>
  
{{note}} Mudlet by design allows duplicate names - so calling permKey with the same name will keep creating new keys. You can check if a key already exists with the [[Manual:Lua_Functions#exists|exists()]] function.  The key will be created even if the lua code does not compile correctly - but this will be apparent as it will be seen in the Editor.
+
==killAlias==
 +
;killAlias(aliasID)
 +
:Deletes a temporary alias with the given ID.
  
==printCmdLine==
+
;Parameters
;printCmdLine(text)
+
* ''aliasID:''
 
+
: The id returned by [[Manual:Lua_Functions#tempAlias|tempAlias]] to identify the alias.
: Replaces the current text in the input line, and sets it to the given text.
 
  
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
printCmdLine("say I'd like to buy ")
+
-- deletes the alias with ID 5
 +
killAlias(5)
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==raiseEvent==
+
==killKey==
;raiseEvent(event_name, arg-1, … arg-n)
+
;killKey(name)
 +
:Deletes a keybinding with the given name. If several keybindings have this name, they'll all be deleted.
  
: Raises the event event_name. The event system will call the main function (the one that is called exactly like the script name) of all such scripts in this profile that have registered event handlers. If an event is raised, but no event handler scripts have been registered with the event system, the event is ignored and nothing happens. This is convenient as you can raise events in your triggers, timers, scripts etc. without having to care if the actual event handling has been implemented yet - or more specifically how it is implemented. Your triggers raise an event to tell the system that they have detected a certain condition to be true or that a certain event has happened. How - and if - the system is going to respond to this event is up to the system and your trigger scripts don’t have to care about such details. For small systems it will be more convenient to use regular function calls instead of events, however, the more complicated your system will get, the more important events will become because they help reduce complexity very much.
+
;Parameters
 +
* ''name:''
 +
: The name or the id returned by [[Manual:Lua_Functions#tempKey|tempKey]] to identify the key.
  
:The corresponding event handlers that listen to the events raised with raiseEvent() need to use the script name as function name and take the correct number of arguments.  
+
{{MudletVersion|3.2}}
  
{{note}} possible arguments can be string, number, boolean, table, function, or nil.
+
<syntaxhighlight lang="lua">
 +
-- make a temp key
 +
local keyid = tempKey(mudlet.key.F8, [[echo("hi!")]])
  
;Example:
+
-- delete the said temp key
 +
killKey(keyid)
 +
</syntaxhighlight>
  
:raiseEvent("fight") a correct event handler function would be: myScript( event_name ). In this example raiseEvent uses minimal arguments, name the event name. There can only be one event handler function per script, but a script can still handle multiple events as the first argument is always the event name - so you can call your own special handlers for individual events. The reason behind this is that you should rather use many individual scripts instead of one huge script that has all your function code etc. Scripts can be organized very well in trees and thus help reduce complexity on large systems.
+
==killTimer==
 +
;killTimer(id)
 +
:Deletes a [[Manual:Lua_Functions#tempTimer|tempTimer]].
  
Where the number of arguments that your event may receive is not fixed you can use [http://www.lua.org/manual/5.1/manual.html#2.5.9 ''...''] as the last argument in the ''function'' declaration to handle any number of arguments. For example:
+
{{note}} Non-temporary timers that you have set up in the GUI or by using [[#permTimer|permTimer]] cannot be deleted with this function. Use [[Manual:Lua_Functions#disableTimer|disableTimer()]] and [[Manual:Lua_Functions#enableTimer|enableTimer()]] to turn them on or off.
  
<syntaxhighlight lang="lua">
+
;Parameters
-- try this function out with "lua myscripthandler(1,2,3,4)"
+
* ''id:'' the ID returned by [[Manual:Lua_Functions#tempTimer|tempTimer]].
function myscripthandler(a, b, ...)
+
 
  print("Arguments a and b are: ", a,b)
+
: Returns true on success and false if the timer id doesn’t exist anymore (timer has already fired) or the timer is not a temp timer.
  -- save the rest of the arguments into a table
+
 
  local otherarguments = {...}
+
;Example
  print("Rest of the arguments are:")
+
<syntaxhighlight lang="lua">
  display(otherarguments)
+
-- create the timer and remember the timer ID
 +
timerID = tempTimer(10, [[echo("hello!")]])
  
  -- access specific otherarguments:
+
-- delete the timer
  print("First and second otherarguments are: ", otherarguments[1], otherarguments[2])
+
killTimer(timerID)
end
+
-- reset the reference to it
 +
timerID = nil
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==raiseGlobalEvent==
+
==killTrigger==
;raiseGlobalEvent(event_name, arg-1, … arg-n)
+
;killTrigger(id)
 +
:Deletes a [[Manual:Lua_Functions#tempTimer|tempTrigger]], or a trigger made with one of the ''temp<type>Trigger()'' functions.
  
: Like [[Manual:Lua_Functions#raiseEvent|raiseEvent()]] this raises the event "event_name", but this event is sent to all '''other''' opened profiles instead. The profiles receive the event in circular alphabetical order (if profile "C" raised this event and we have profiles "A", "C", and "E", the order is "E" -> "A", but if "E" raised the event the order would be "A" -> "C"); execution control is handed to the receiving profiles so that means that long running events may lock up the profile that raised the event.
+
{{note}} When used in out of trigger contexts, the triggers are disabled and deleted upon the next line received from the game - so if you are testing trigger deletion within an alias, the 'statistics' window will be reporting trigger counts that are disabled and pending removal, and thus are no cause for concern.
  
: The sending profile's name is automatically appended as the last argument to the event.
+
;Parameters
 +
* ''id:''
 +
: The ID returned by a ''temp<type>Trigger'' to identify the item. ID is a string and not a number.
 +
 
 +
:Returns true on success and false if the trigger id doesn’t exist anymore (trigger has already fired) or the trigger is not a temp trigger.
 +
 
 +
{{note}} As of Mudlet version 4.16.0, triggers created with [[#tempComplexRegexTrigger|tempComplexRegexTrigger]] can only be killed using the name string specified during creation.
 +
 
 +
==permAlias==
 +
;permAlias(name, parent, regex, lua code)
  
;Example:
+
:Creates a persistent alias that stays after Mudlet is restarted and shows up in the Script Editor.
  
 +
;Parameters
 +
* ''name:''
 +
: The name you’d like the alias to have.
 +
* ''parent:''
 +
: The name of the group, or another alias you want the trigger to go in - however if such a group/alias doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
 +
* ''regex:''
 +
: The pattern that you’d like the alias to use.
 +
* ''lua code:''
 +
: The script the alias will do when it matches.
 +
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- from profile called "My MUD" this raises an event "my event" with additional arguments 1, 2, 3, "My MUD" to all profiles except the original one
+
-- creates an alias called "new alias" in a group called "my group"
raiseGlobalEvent("my event", 1, 2, 3)
+
permAlias("new alias", "my group", "^test$", [[echo ("say it works! This alias will show up in the script editor too.")]])
 
</syntaxhighlight>
 
</syntaxhighlight>
  
{{Note}} Available since Mudlet 3.1.0.
+
{{note}} Mudlet by design allows duplicate names - so calling permAlias with the same name will keep creating new aliases. You can check if an alias already exists with the [[Manual:Lua_Functions#exists|exists]] function.
  
Tip: you might want to add the [[Manual:Miscellaneous_Functions#getProfileName|profile name]] to your plain [[Manual:Miscellaneous_Functions#raiseEvent|raiseEvent()]] arguments. This'll help you tell which profile your event came from similar to [[#raiseGlobalEvent|raiseGlobalEvent()]].
+
==permGroup==
 +
;permGroup(name, itemtype, [parent])
  
==remainingTime==
+
:Creates a new group of a given type. This group will persist through Mudlet restarts.
;remainingTime(timer id number or name)
+
;Parameters
 +
* ''name'':
 +
: The name of the new group item you want to create.
 +
* ''itemtype'' :
 +
: The type of the item, can be one of the following:
 +
:: trigger
 +
:: alias
 +
:: timer
 +
:: script (available in Mudlet 4.7+)
 +
:: key (available in Mudlet 4.11+)
 +
* ''parent'' (available in Mudlet 3.1+):
 +
: (optional) Name of existing item which the new item will be created as a child of. If none is given, item will be at the root level (not nested in any other groups)
  
: Returns the remaining time in floating point form in seconds (if it is active) for the timer (temporary or permanent) with the id number or the (first) one found with the name.
+
;Example
: If the timer is inactive or has expired or is not found it will return a ''nil'' and an ''error message''. It, theoretically could also return 0 if the timer is overdue, i.e. it has expired but the internal code has not yet been run but that has not been seen in during testing. Permanent ''offset timers'' will only show as active during the period when they are running after their parent has expired and started them.
+
<syntaxhighlight lang="lua">
 +
--create a new trigger group
 +
permGroup("Combat triggers", "trigger")
  
{{Note}} Available in Mudlet since TBA.
+
--create a new alias group only if one doesn't exist already
 +
if exists("Defensive aliases", "alias") == 0 then
 +
  permGroup("Defensive aliases", "alias")
 +
end
 +
</syntaxhighlight>
  
;Example:
+
==permPromptTrigger==
 +
;permPromptTrigger(name, parent, lua code)
 +
:Creates a persistent trigger for the in-game prompt that stays after Mudlet is restarted and shows up in the Script Editor.
  
<syntaxhighlight lang="lua">
+
{{note}} If the trigger is not working, check that the '''N:''' bottom-right has a number. This feature requires telnet Go-Ahead (GA) or End-of-Record (EOR) to be enabled in your game. Available in Mudlet 3.6+
tid = tempTimer(600, [[echo("\nYour ten minutes are up.\n")]])
 
echo("\nYou have " .. remainingTime(tid) .. " seconds left, use it wisely... \n")
 
  
-- Will produce something like:
+
;Parameters:
 +
* ''name'' is the name you’d like the trigger to have.
 +
* ''parent'' is the name of the group, or another trigger you want the trigger to go in - however if such a group/trigger doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
 +
* ''lua code'' is the script the trigger will do when it matches.
  
You have 599.923 seconds left, use it wisely...
+
;Example:
 +
<syntaxhighlight lang="lua">
 +
permPromptTrigger("echo on prompt", "", [[echo("hey! this thing is working!\n")]])
 +
</syntaxhighlight>
  
-- Then ten minutes time later:
 
  
Your ten minutes are up.
+
==permRegexTrigger==
 +
;permRegexTrigger(name, parent, pattern table, lua code)
 +
:Creates a persistent trigger with one or more ''regex'' patterns that stays after Mudlet is restarted and shows up in the Script Editor.
  
 +
;Parameters
 +
* ''name'' is the name you’d like the trigger to have.
 +
* ''parent'' is the name of the group, or another trigger you want the trigger to go in - however if such a group/trigger doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
 +
* ''pattern table'' is a table of patterns that you’d like the trigger to use - it can be one or many.
 +
* ''lua code'' is the script the trigger will do when it matches.
 +
;Example
 +
<syntaxhighlight lang="lua">
 +
-- Create a regex trigger that will match on the prompt to record your status
 +
permRegexTrigger("Prompt", "", {"^(\\d+)h, (\\d+)m"}, [[health = tonumber(matches[2]); mana = tonumber(matches[3])]])
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
{{note}} Mudlet by design allows duplicate names - so calling permRegexTrigger with the same name will keep creating new triggers. You can check if a trigger already exists with the [[Manual:Lua_Functions#exists|exists()]] function.
  
==resetProfileIcon==
+
==permBeginOfLineStringTrigger==
;resetProfileIcon()
+
;permBeginOfLineStringTrigger(name, parent, pattern table, lua code)
: Resets the profile's icon in the connection screen to default.
+
:Creates a persistent trigger that stays after Mudlet is restarted and shows up in the Script Editor. The trigger will go off whenever one of the ''regex'' patterns it's provided with matches. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls.
  
See also: [[#setProfileIcon|setProfileIcon()]].
+
;Parameters
 +
* ''name'' is the name you’d like the trigger to have.
 +
* ''parent'' is the name of the group, or another trigger you want the trigger to go in - however if such a group/trigger doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
 +
* ''pattern table'' is a table of patterns that you’d like the trigger to use - it can be one or many.
 +
* ''lua code'' is the script the trigger will do when it matches.
  
{{Note}} Available in Mudlet 4.0+.
+
;Examples
 +
<syntaxhighlight lang="lua">
 +
-- Create a trigger that will match on anything that starts with "You sit" and do "stand".
 +
-- It will not go into any groups, so it'll be on the top.
 +
permBeginOfLineStringTrigger("Stand up", "", {"You sit"}, [[send ("stand")]])
  
;Example:
+
-- Another example - lets put our trigger into a "General" folder and give it several patterns.
 
+
permBeginOfLineStringTrigger("Stand up", "General", {"You sit", "You fall", "You are knocked over by"}, [[send ("stand")]])
<syntaxhighlight lang="lua">
 
resetProfileIcon()
 
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
{{note}} Mudlet by design allows duplicate names - so calling permBeginOfLineStringTrigger with the same name will keep creating new triggers. You can check if a trigger already exists with the [[Manual:Lua_Functions#exists|exists()]] function.
  
==resetStopWatch==
+
==permSubstringTrigger==
;resetStopWatch(watchID)
+
;permSubstringTrigger( name, parent, pattern table, lua code )
:This function resets the time to 0:0:0.0, but does not start the stop watch. You can start it with [[Manual:Lua_Functions#startStopWatch | startStopWatch]] → [[Manual:Lua_Functions#createStopWatch | createStopWatch]]
+
:Creates a persistent trigger with one or more ''substring'' patterns that stays after Mudlet is restarted and shows up in the Script Editor.
 
 
==setConsoleBufferSize==
 
;setConsoleBufferSize(consoleName, linesLimit, sizeOfBatchDeletion)
 
:Sets the maximum number of lines a buffer (main window or a miniconsole) can hold. Default is 10,000.
 
 
 
 
;Parameters
 
;Parameters
* ''consoleName:''
+
* ''name'' is the name you’d like the trigger to have.
: (optional) The name of the window. If omitted, uses the main console.
+
* ''parent'' is the name of the group, or another trigger you want the trigger to go in - however if such a group/trigger doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
* ''linesLimit:''
+
* ''pattern table'' is a table of patterns that you’d like the trigger to use - it can be one or many.
: Sets the amount of lines the buffer should have.  
+
* ''lua code'' is the script the trigger will do when it matches.
{{note}} Mudlet performs extremely efficiently with even huge numbers, so your only limitation is your computers memory (RAM).
 
* ''sizeOfBatchDeletion:''
 
: Specifies how many lines should Mudlet delete at once when you go over the limit - it does it in bulk because it's efficient to do so.
 
 
 
 
;Example
 
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- sets the main windows size to 5 million lines maximum - which is more than enough!
+
-- Create a trigger to highlight the word "pixie" for us
setConsoleBufferSize("main", 5000000, 1000)
+
permSubstringTrigger("Highlight stuff", "General", {"pixie"},
 +
[[selectString(line, 1) bg("yellow") resetFormat()]])
 +
 
 +
-- Or another trigger to highlight several different things
 +
permSubstringTrigger("Highlight stuff", "General", {"pixie", "cat", "dog", "rabbit"},
 +
[[selectString(line, 1) fg ("blue") bg("yellow") resetFormat()]])
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
{{note}} Mudlet by design allows duplicate names - so calling permSubstringTrigger with the same name will keep creating new triggers. You can check if a trigger already exists with the [[Manual:Lua_Functions#exists|exists()]] function.
  
==setProfileIcon==
+
==permScript==
;setProfileIcon(iconPath)
+
;permScript(name, parent, lua code)
:Set a custom icon for this profile in the connection screen.  
+
: Creates a new script in the Script Editor that stays after Mudlet is restarted.
  
:Returns true if successful, or nil+error message if not.
+
;Parameters
 +
* ''name'': name of the script.
 +
* ''parent'': name of the script group you want the script to go in.
 +
* ''lua code'': is the code with string you are putting in your script.
  
:See also: [[#resetProfileIcon|resetProfileIcon()]].
+
;Returns
 +
* a unique id number for that script.
  
{{note}} Available in Mudlet 4.0+
+
: See also: [[#enableScript|enableScript()]], [[#exists|exists()]], [[#appendScript|appendScript()]], [[#disableScript|disableScript()]], [[#getScript|getScript()]], [[#setScript|setScript()]]
  
;Parameters
+
;Example:
* ''iconPath:''
+
<syntaxhighlight lang="lua">
: Full location of the icon - can be .png or .jpg with ideal dimensions of 120x30.
+
-- create a script in the "first script group" group
 +
permScript("my script", "first script group", [[send ("my script that's in my first script group fired!")]])
 +
-- create a script that's not in any group; just at the top
 +
permScript("my script", "", [[send ("my script that's in my first script group fired!")]])
  
;Example
+
-- enable Script - a script element is disabled at creation
<syntaxhighlight lang="lua">
+
enableScript("my script")
-- set a custom icon that is located in an installed package called "mypackage"
 
setProfileIcon(getMudletHomeDir().."/mypackage/icon.png")
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==setStopWatchName==
+
{{note}} The script is called once but NOT active after creation, it will need to be enabled by [[#enableScript|enableScript()]].
;setStopWatchPersistence( watchID/currentStopWatchName, newStopWatchName ) from Mudlet TBA
+
 
 +
{{note}} Mudlet by design allows duplicate names - so calling permScript with the same name will keep creating new script elements. You can check if a script already exists with the [[Manual:Lua_Functions#exists|exists()]] function.
  
;Parameters
+
{{note}} If the ''lua code'' parameter is an empty string, then the function will create a script group instead.
* ''watchID'' (number) / ''currentStopWatchName'' (string): The stopwatch ID you get from [[Manual:Lua_Functions#createStopWatch|createStopWatch()]] or the name supplied to that function at that time, or previously applied with this function.
 
* ''newStopWatchName'' (string): The name to use for this stopwatch from now on.
 
  
;Returns
 
* ''true'' on success, ''nil'' and an error message if no matching stopwatch is found.
 
  
{{note}} Either ''currentStopWatchName'' or ''newStopWatchName'' may be empty strings: if the first of these is so then the ''lowest'' ID numbered stopwatch without a name is chosen; if the second is so then an existing name is removed from the chosen stopwatch.
+
{{MudletVersion|4.8}}
  
==setStopWatchPersistence==
+
==permTimer==
;setStopWatchPersistence( watchID/watchName, state ) from Mudlet TBA
+
;permTimer(name, parent, seconds, lua code)
 +
: Creates a persistent timer that stays after Mudlet is restarted and shows up in the Script Editor.
  
 
;Parameters
 
;Parameters
* ''watchID'' (number) / ''watchName'' (string): The stopwatch ID you get from [[Manual:Lua_Functions#createStopWatch|createStopWatch()]] or the name supplied to that function or applied later with [[Manual:Lua_Functions#setStopWatchName|setStopWatchName()]]
+
* ''name''  
* ''state'' (boolean): if ''true'' the stopWatch will be saved.
+
:name of the timer.
 +
* ''parent''  
 +
:name of the timer group you want the timer to go in.
 +
* ''seconds''  
 +
:a floating point number specifying a delay in seconds after which the timer will do the lua code (stored as the timer's "script") you give it as a string.
 +
* ''lua code'' is the code with string you are doing this to.
  
 
;Returns
 
;Returns
* ''true'' on success, ''nil'' and an error message if no matching stopwatch is found.
+
* a unique id number for that timer.
  
:Sets or resets the flag so that the stopwatch is saved between sessions or after a [[Manual:Miscellaneous_Functions#resetProfile|resetProfile()]] call. If set then, if ''stopped'' the elapsed time recorded will be unchanged when the stopwatch is reloaded in the next session; if ''running'' the elapsed time will continue to increment and it will include the time that the profile was not loaded, therefore it can be used to measure events in real-time, outside of the profile!
+
;Example:
 +
<syntaxhighlight lang="lua">
 +
-- create a timer in the "first timer group" group
 +
permTimer("my timer", "first timer group", 4.5, [[send ("my timer that's in my first timer group fired!")]])
 +
-- create a timer that's not in any group; just at the top
 +
permTimer("my timer", "", 4.5, [[send ("my timer that's in my first timer group fired!")]])
  
{{note}} When a persistent stopwatch is reloaded in a later session (or after a use of ''resetProfile()'') the stopwatch may not be allocated the same ID number as before - therefore it is advisable to assign any persistent stopwatches a name, either when it is created or before the session is ended.
+
-- enable timer - they start off disabled until you're ready
 +
enableTimer("my timer")
 +
</syntaxhighlight>
  
==setTriggerStayOpen==
+
{{note}} The timer is NOT active after creation, it will need to be enabled by a call to [[#enableTimer|enableTimer()]] before it starts.
;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
+
{{note}} Mudlet by design allows duplicate names - so calling permTimer with the same name will keep creating new timers. You can check if a timer already exists with the [[Manual:Lua_Functions#exists|exists()]] function.
* ''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
+
==permKey==
<syntaxhighlight lang="lua">
+
;permKey(name, parent, [modifier], key code, lua code)
-- if you have a trigger that opens a chain (has some fire length) and you'd like it to be closed
+
: Creates a persistent key that stays after Mudlet is restarted and shows up in the Script Editor.
-- 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!
 
</syntaxhighlight>
 
  
==startStopWatch==
+
;Parameters
;startStopWatch( watchID ) - up to TBA
+
* ''name''
 +
:name of the key.
 +
* ''parent''
 +
:name of the timer group you want the timer to go in or "" for the top level.
 +
* ''modifier''
 +
:(optional) modifier to use - can be one of ''mudlet.keymodifier.Control'', ''mudlet.keymodifier.Alt'', ''mudlet.keymodifier.Shift'', ''mudlet.keymodifier.Meta'', ''mudlet.keymodifier.Keypad'', or ''mudlet.keymodifier.GroupSwitch'' or the default value of ''mudlet.keymodifier.None'' which is used if the argument is omitted. To use multiple modifiers, add them together: ''(mudlet.keymodifier.Shift + mudlet.keymodifier.Control)''
 +
* ''key code''
 +
: actual key to use - one of the values available in ''mudlet.key'', e.g. ''mudlet.key.Escape'', ''mudlet.key.Tab'', ''mudlet.key.F1'', ''mudlet.key.A'', and so on. The list is a bit long to list out in full so it is [https://github.com/Mudlet/Mudlet/blob/development/src/mudlet-lua/lua/KeyCodes.lua#L2 available here].
 +
: set to -1 if you want to create a key folder instead.
 +
* ''lua code'
 +
: code you would like the key to run.
  
:Starts the stop watch. Each time this function is called the stopwatch is reset to zero and restarted.
+
;Returns
 +
* a unique id number for that key.
  
;startStopWatch( watchID, [resetAndRestart = ''true''] ) - from TBA
+
{{MudletVersion|3.2+, creating key folders in Mudlet 4.10}}
;startStopWatch( watchName )
 
  
:Stopwatches can be stopped (with [[Manual:Lua_Functions#stopStopWatch|stopStopWatch()]]) and then re-started any number of times. '''To ensure backwards compatibility, if the stopwatch is identified by a ''numeric'' argument then, ''unless a second argument of false is supplied as well'' this function will also reset the stopwatch to zero and restart it - whether it is running or not'''; otherwise only a stopped watch can be started and only a started watch may be stopped. Trying to repeat either will produce a nil and an error message instead; also the recorded time is no longer reset so that they can now be used to record a total of isolated periods of time like a real stopwatch.
+
;Example:
 +
<syntaxhighlight lang="lua">
 +
-- create a key at the top level for F8
 +
permKey("my key", "", mudlet.key.F8, [[echo("hey this thing actually works!\n")]])
  
:See also: [[Manual:Lua_Functions#createStopWatch|createStopWatch()]], [[Manual:Lua_Functions#stopStopWatch|stopStopWatch()]]
+
-- or Ctrl+F8
 +
permKey("my key", "", mudlet.keymodifier.Control, mudlet.key.F8, [[echo("hey this thing actually works!\n")]])
  
;Parameters
+
-- Ctrl+Shift+W
* ''watchID''/''watchName'': The stopwatch ID you get with [[Manual:Lua_Functions#createStopWatch|createStopWatch()]], or from TBA the name assigned with that function or [[Manual:Lua_Functions#setStopWatchName|setStopWatchName()]].
+
permKey("jump keybinding", "", mudlet.keymodifier.Control + mudlet.keymodifier.Shift, mudlet.key.W, [[send("jump")]])
* ''resetAndRestart'': Boolean flag needed (as ''false'') to make the function from TBA, when supplied with a numeric watch ID, to '''not''' reset the stopwatch and only start a previously stopped stopwatch. This behavior is automatic when a string watch name is used to identify the stopwatch but differs from how the function behaved prior to that version.
 
 
 
;Returns
 
* ''true'' on success, ''nil'' and an error message if no matching stopwatch is found or if it cannot be started (because the later style behavior was indicated and it was already running).
 
 
 
;Examples
 
<syntaxhighlight lang="lua">
 
-- this is a common pattern for re-using stopwatches prior to TBA and starting them:
 
watch = watch or createStopWatch()
 
startStopWatch(watch)
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
:: After TBA it will be necessary to call ''stopStopWatch(...)'' and then ''resetStopWatch(...)'' before using ''startStopWatch(...)'' to re-use the stopwatch, '''this is thus not quite the same behavior but it is more consistent with the model of how a real stopwatch would act.'''
+
{{note}} Mudlet by design allows duplicate names - so calling permKey with the same name will keep creating new keys. You can check if a key already exists with the [[Manual:Lua_Functions#exists|exists()]] function. The key will be created even if the lua code does not compile correctly - but this will be apparent as it will be seen in the Editor.
  
==stopStopWatch==
+
==printCmdLine==
;stopStopWatch( watchID [or watchName from TBA])
+
;printCmdLine([name], text)
:"Stops" (though see the note below) the stop watch and returns (only the '''first''' time it is called after the stopwatch has been set running with [[Manual:Lua_Functions#startStopWatch()|startStopWatchTime()]]) the elapsed time as a number of seconds, with a decimal portion give a resolution in milliseconds (thousandths of a second). You can also retrieve the current time without stopping the stopwatch with [[Manual:Lua_Functions#getStopWatchTime|getStopWatchTime()]] or, since TBA [[Manual:Lua_Functions#getBrokenDownStopWatchTime|getBrokenDownStopWatchTime()]].
 
  
:See also: [[Manual:Lua_Functions#createStopWatch|createStopWatch()]]
+
: Replaces the current text in the input line, and sets it to the given text.
 +
: See also: [[Manual:Lua_Functions#clearCmdLine|clearCmdLine()]], [[#appendCmdLine|appendCmdLine()]]
  
 
;Parameters
 
;Parameters
* ''watchID:'' The stopwatch ID you get with [[Manual:Lua_Functions#createStopWatch|createStopWatch()]] or from Mudlet TBA the name given to that function or later set with [[Manual:Lua_Functions#setStopWatchName|setStopWatchName()]].
+
* ''name'': (optional) name of the command line. If not given, main commandline's text will be set.
 +
* ''text'': text to set
  
;Returns
+
<syntaxhighlight lang="lua">
* the elapsed time as a floating-point number of seconds - it may be negative if the time was previously adjusted/preset to a negative amount (with [[Manual:Lua_Functions#adjustStopWatch|adjustStopWatch()]]) and that period has not yet elapsed.
+
printCmdLine("say I'd like to buy ")
* (from Mudlet TBA) ''nil'' and an error message if the stopwatch is already stopped by a previous call to stopStopWatch.
+
</syntaxhighlight>
  
;Examples
+
==raiseEvent==
<syntaxhighlight lang="lua">
+
;raiseEvent(event_name, arg-1, … arg-n)
-- this is a common pattern for re-using stopwatches and starting them:
 
watch = watch or createStopWatch()
 
startStopWatch(watch)
 
  
-- do some long-running code here ...
+
: Raises the event event_name. The event system will call the main function (the one that is called exactly like the script name) of all such scripts in this profile that have registered event handlers. If an event is raised, but no event handler scripts have been registered with the event system, the event is ignored and nothing happens. This is convenient as you can raise events in your triggers, timers, scripts etc. without having to care if the actual event handling has been implemented yet - or more specifically how it is implemented. Your triggers raise an event to tell the system that they have detected a certain condition to be true or that a certain event has happened. How - and if - the system is going to respond to this event is up to the system and your trigger scripts don’t have to care about such details. For small systems it will be more convenient to use regular function calls instead of events, however, the more complicated your system will get, the more important events will become because they help reduce complexity very much.
  
print("The code took: "..stopStopWatch(watch).."s to run.")
+
:The corresponding event handlers that listen to the events raised with raiseEvent() need to use the script name as function name and take the correct number of arguments.  
</syntaxhighlight>
 
  
{{Note}} Prior to TBA the implementation was broken in that it was NOT possible to really stop a stopwatch - it behaved the same as the ''getStopWatchTime()'' command the ''first'' time it was used but if called again before ''startStopWatchTime()'' was used to reset and restart the stopwatch the value returned was instead a random, meaningless, value.
+
:See also: [[#raiseGlobalEvent|raiseGlobalEvent]]
  
==tempAnsiColorTrigger==
+
{{note}} possible arguments can be string, number, boolean, table, function, or nil.
;tempAnsiColorTrigger(foregroundColor, backgroundColor, code, expireAfter)
 
:This is an alternative to [[Manual:Lua_Functions#tempColorTrigger|tempColorTrigger()]] which supports the full set of 256 ANSI color codes directly and makes a color trigger that triggers on the specified foreground and background color. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
 
  
;Parameters
+
;Example:
* ''foregroundColor:'' The foreground color you'd like to trigger on.
 
* ''backgroundColor'': The background color you'd like to trigger on.
 
* ''code to do'': The code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function.
 
* ''expireAfter'': Delete trigger after a specified number of matches. You can make a trigger match not count towards expiration by returning true after it fires.
 
  
;Color codes (note that the values greater than or equal to zero are the actual number codes that ANSI and the game server uses for the 8/16/256 color modes)
+
:raiseEvent("fight") a correct event handler function would be: myScript( event_name ). In this example raiseEvent uses minimal arguments, name the event name. There can only be one event handler function per script, but a script can still handle multiple events as the first argument is always the event name - so you can call your own special handlers for individual events. The reason behind this is that you should rather use many individual scripts instead of one huge script that has all your function code etc. Scripts can be organized very well in trees and thus help reduce complexity on large systems.
  
::Special codes (may be extended in the future):
+
Where the number of arguments that your event may receive is not fixed you can use [http://www.lua.org/manual/5.1/manual.html#2.5.9 ''...''] as the last argument in the ''function'' declaration to handle any number of arguments. For example:
:::-2 = default text color (what is used after an ANSI SGR 0 m code that resets the foreground and background colors to those set in the preferences)
 
:::-1 = ignore (only '''one''' of the foreground or background codes can have this value - otherwise it would not be a ''color'' trigger!)
 
  
::ANSI 8-color set:
+
<syntaxhighlight lang="lua">
:::0 = (dark) black
+
-- try this function out with "lua myscripthandler(1,2,3,4)"
:::1 = (dark) red
+
function myscripthandler(a, b, ...)
:::2 = (dark) green
+
  print("Arguments a and b are: ", a,b)
:::3 = (dark) yellow
+
  -- save the rest of the arguments into a table
:::4 = (dark) blue
+
  local otherarguments = {...}
:::5 = (dark) magenta
+
  print("Rest of the arguments are:")
:::6 = (dark) cyan
+
  display(otherarguments)
:::7 = (dark) white {a.k.a. light gray}
 
  
::Additional colors in 16-color set:
+
  -- access specific otherarguments:
:::8 = light black {a.k.a. dark gray}
+
  print("First and second otherarguments are: ", otherarguments[1], otherarguments[2])
:::9 = light red
+
end
:::10 = light green
+
</syntaxhighlight>
:::11 = light yellow
 
:::12 = light blue
 
:::13 = light magenta
 
:::14 = light cyan
 
:::15 = light white
 
  
::6 x 6 x 6 RGB (216) colors, shown as a 3x2-digit hex code
+
==raiseGlobalEvent==
:::16 = #000000
+
;raiseGlobalEvent(event_name, arg-1, … arg-n)
:::17 = #000033
 
:::18 = #000066
 
:::...
 
:::229 = #FFFF99
 
:::230 = #FFFFCC
 
:::231 = #FFFFFF
 
  
::24 gray-scale, also show as a 3x2-digit hex code
+
: Like [[Manual:Lua_Functions#raiseEvent|raiseEvent()]] this raises the event "event_name", but this event is sent to all '''other''' opened profiles instead. The profiles receive the event in circular alphabetical order (if profile "C" raised this event and we have profiles "A", "C", and "E", the order is "E" -> "A", but if "E" raised the event the order would be "A" -> "C"); execution control is handed to the receiving profiles so that means that long running events may lock up the profile that raised the event.
:::232 = #000000
+
 
:::233 = #0A0A0A
+
: The sending profile's name is automatically appended as the last argument to the event.
:::234 = #151515
+
 
:::...
+
{{note}} possible arguments can be string, number, boolean, or nil, but not table or function.
:::253 = #E9E9E9
+
 
:::254 = #F4F4F4
+
;Example:
:::255 = #FFFFFF
 
  
;Examples
 
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- This script will re-highlight all text in a light cyan foreground color on any background with a red foreground color
+
-- from profile called "My game" this raises an event "my event" with additional arguments 1, 2, 3, "My game" to all profiles except the original one
-- until another foreground color in the current line is being met. temporary color triggers do not offer match_all
+
raiseGlobalEvent("my event", 1, 2, 3)
-- 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.
 
tempAnsiColorTrigger(14, -1, [[selectString(matches[1],1) fg("red")]])
 
-- or:
 
tempAnsiColorTrigger(14, -1, function()
 
  selectString(matches[1], 1)
 
  fg("red")
 
end)
 
  
-- match the trigger only 4 times
+
-- want the current profile to receive it as well? Use raiseEvent
tempColorTrigger(14, -1, [[selectString(matches[1],1) fg("red")]], 4)
+
raiseEvent("my event", 1, 2, 3)
 
</syntaxhighlight>
 
</syntaxhighlight>
  
{{note}} Available since Mudlet 3.17+
+
<syntaxhighlight lang="lua>
 +
-- example of calling functions in one profile from another:
 +
-- profile B:
 +
control = control or {}
 +
function control.updateStatus()
 +
  disableTrigger("test triggers")
 +
  print("disabling triggers worked!")
 +
end
  
==tempAlias==
+
-- this handles calling the right function in the control table
;aliasID = tempAlias(regex, code to do)
+
function control.marshaller(_, callfunction)
:Creates a temporary alias - temporary in the sense that it won't be saved when Mudlet restarts (unless you re-create it). The alias will go off as many times as it matches, it is not a one-shot alias. The function returns an ID for subsequent [[Manual:Lua_Functions#enableAlias|enableAlias()]], [[Manual:Lua_Functions#disableAlias|disableAlias()]] and [[Manual:Lua_Functions#killAlias|killAlias()]] calls.
+
  if control[callfunction] then control[callfunction]()
 +
  else
 +
    cecho("<red>Asked to call an unknown function: "..callfunction)
 +
  end
 +
end
  
;Parameters
+
registerAnonymousEventHandler("sysSendAllProfiles", "control.marshaller")
* ''regex:'' Alias pattern in regex.
+
 
* ''code to do:'' The code to do when the alias fires - wrap it in [[ ]].
+
-- profile A:
 +
raiseGlobalEvent("sysSendAllProfiles", "updateStatus")
 +
raiseGlobalEvent("sysSendAllProfiles", "invalidfunction")
 +
</syntaxhighlight>
 +
 
 +
{{MudletVersion|3.1.0}}
 +
 
 +
Tip: you might want to add the [[Manual:Miscellaneous_Functions#getProfileName|profile name]] to your plain [[Manual:Miscellaneous_Functions#raiseEvent|raiseEvent()]] arguments. This'll help you tell which profile your event came from similar to [[#raiseGlobalEvent|raiseGlobalEvent()]].
 +
 
 +
==registerNamedTimer==
 +
; success = registerNamedTimer(userName, timerName, time, functionReference, [repeating])
  
;Examples
+
:Registers a named timer with name timerName. Named timers are protected from duplication and can be stopped and resumed, unlike normal tempTimers. A separate list is kept for each userName, to enforce name spacing and avoid collisions
<syntaxhighlight lang="lua">
 
myaliasID = tempAlias("^hi$", [[send ("hi") echo ("we said hi!")]])
 
  
-- you can also delete the alias later with:
+
;See also: [[Manual:Lua_Functions#tempTimer|tempTimer()]], [[Manual:Lua_Functions#stopNamedTimer|stopNamedTimer()]], [[Manual:Lua_Functions#resumeNamedTimer|resumeNamedTimer()]], [[Manual:Lua_Functions#deleteNamedTimer|deleteNamedTimer()]], [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]]
killAlias(myaliasID)
 
</syntaxhighlight>
 
  
==tempBeginOfLineTrigger==
+
{{MudletVersion|4.14}}
;tempBeginOfLineTrigger(part of line, code, expireAfter)
 
:Creates a trigger that will go off whenever the part of line it's provided with matches the line right from the start (doesn't matter what the line ends with). The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls.
 
  
 
;Parameters
 
;Parameters
* ''part of line'': start of the line that you'd like to match. This can also be regex.
+
* ''userName:''
* ''code to do'': code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5.0).
+
: The user name the event handler was registered under.
* ''expireAfter'': Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
+
* ''timerName:''
 +
: The name of the handler. Used to reference the handler in other functions and prevent duplicates. Recommended you use descriptive names, "hp" is likely to collide with something else, "DemonVitals" less so.
 +
* ''time:''
 +
: The amount of time in seconds to wait before firing.
 +
* ''functionReference:''
 +
: The function reference to run when the event comes in. Can be the name of a function, "handlerFunction", or the lua function itself.
 +
* ''repeating:''
 +
: (optional) if true, the timer continue to fire until the stop it using [[Manual:Lua_Functions#stopNamedTimer|stopNamedTimer()]]
 +
;Returns
 +
* true if successful, otherwise errors.
  
;Examples
+
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
mytriggerID = tempBeginOfLineTrigger("Hello", [[echo("We matched!")]])
+
-- establish a named timer called "Check balance" which runs balanceChecker() after 1 second
 +
-- it is started automatically when registered, and fires only once despite being run twice
 +
-- you wouldn't do this intentionally, but illustrates the duplicate protection
 +
registerNamedTimer("Demonnic", "Check Balance", 1, balanceChecker)
 +
registerNamedTimer("Demonnic", "Check Balance", 1, balanceChecker)
  
--[[ now this trigger will match on any of these lines:
+
-- then the next time you want to make/use the same timer, you can shortcut it with
Hello
+
resumeNamedTimer("Demonnic", "Check Balance")
Hello!
+
</syntaxhighlight>
Hello, Bob!
+
 
 +
==remainingTime==
 +
;remainingTime(timer id number or name)
 +
 
 +
: Returns the remaining time in floating point form in seconds (if it is active) for the timer (temporary or permanent) with the id number or the (first) one found with the name.
 +
: If the timer is inactive or has expired or is not found it will return a ''nil'' and an ''error message''. It, theoretically could also return 0 if the timer is overdue, i.e. it has expired but the internal code has not yet been run but that has not been seen in during testing. Permanent ''offset timers'' will only show as active during the period when they are running after their parent has expired and started them.
  
but not on:
+
{{MudletVersion|3.20}}
Oh, Hello
 
Oh, Hello!
 
]]
 
  
-- or as a function:
+
;Example:
mytriggerID = tempBeginOfLineTrigger("Hello", function() echo("We matched!") end)
 
</syntaxhighlight>
 
  
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- you can make the trigger match only a certain amount of times as well, 5 in this example:
+
tid = tempTimer(600, [[echo("\nYour ten minutes are up.\n")]])
tempBeginOfLineTrigger("This is the start of the line", function() echo("We matched!") end, 5)
+
echo("\nYou have " .. remainingTime(tid) .. " seconds left, use it wisely... \n")
 +
 
 +
-- Will produce something like:
  
-- if you want a trigger match not to count towards expiration, return true. In this example it'll match 5 times unless the line is "Start of line and this is the end."
+
You have 599.923 seconds left, use it wisely...  
tempBeginOfLineTrigger("Start of line",
 
function()
 
  if line == "Start of line and this is the end." then
 
    return true
 
  else
 
    return false
 
  end
 
end, 5)
 
</syntaxhighlight>
 
  
==tempButton==
+
-- Then ten minutes time later:
;tempButton(toolbar name, button text, orientation)
 
:Creates a temporary button. Temporary means, it will disappear when Mudlet is closed.
 
  
;Parameters:
+
Your ten minutes are up.
* ''toolbar name'': The name of the toolbar to place the button into.
 
* ''button text'': The text to display on the button.
 
* ''orientation'': a number 0 or 1 where 0 means horizontal orientation for the button and 1 means vertical orientation for the button. This becomes important when you want to have more than one button in the same toolbar.
 
  
;Example
 
<syntaxhighlight lang="lua">
 
-- makes a temporary toolbar with two buttons at the top of the main Mudlet window
 
lua tempButtonToolbar("topToolbar", 0, 0)
 
lua tempButton("topToolbar", "leftButton", 0)
 
lua tempButton("topToolbar", "rightButton", 0)
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==tempButtonToolbar==
+
==resetProfileIcon==
;tempButtonToolbar(name, location, orientation)
+
;resetProfileIcon()
:Creates a temporary button toolbar. Temporary means, it will disappear when Mudlet is closed.
+
: Resets the profile's icon in the connection screen to default.
 +
 
 +
See also: [[#setProfileIcon|setProfileIcon()]].
 +
 
 +
{{MudletVersion|4.0}}
  
;Parameters:
+
;Example:
* ''name'': The name of the toolbar.
 
* ''location'': a number from 0 to 4, where 0 means "at the top of the screen", 1 means "left side", 2 means "right side" and 3 means "in a window of its own" which can be dragged and attached to the main Mudlet window if needed.
 
* ''orientation'': a number 0 or 1, where 0 means horizontal orientation for the toolbar and 1 means vertical orientation for the toolbar. This becomes important when you want to have more than one toolbar in the same location of the window.
 
  
;Example
 
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- makes a temporary toolbar with two buttons at the top of the main Mudlet window
+
resetProfileIcon()
lua tempButtonToolbar("topToolbar", 0, 0)
 
lua tempButton("topToolbar", "leftButton", 0)
 
lua tempButton("topToolbar", "rightButton", 0)
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==tempColorTrigger==
+
==resetStopWatch==
;tempColorTrigger(foregroundColor, backgroundColor, code, expireAfter)
+
;resetStopWatch(watchID)
:Makes a color trigger that triggers on the specified foreground and background color. Both colors need to be supplied in form of these simplified ANSI 16 color mode codes. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
+
:This function resets the time to 0:0:0.0, but does not stop or start the stop watch. You can stop it with [[Manual:Lua_Functions#stopStopWatch | stopStopWatch]] or start it with [[Manual:Lua_Functions#startStopWatch | startStopWatch]] [[Manual:Lua_Functions#createStopWatch | createStopWatch]]
 +
 
 +
==resumeNamedTimer==
 +
; success = resumeNamedTimer(userName, handlerName)
  
;Parameters
+
:Resumes a named timer with name handlerName and causes it to fire again. One time unless it was registered as repeating.
* ''foregroundColor:'' The foreground color you'd like to trigger on.
 
* ''backgroundColor'': The background color you'd like to trigger on.
 
* ''code to do'': The code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5.0).
 
* ''expireAfter'': Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
 
  
;Color codes
+
;See also: [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]], [[Manual:Lua_Functions#stopNamedTimer|stopNamedTimer()]]
 +
 
 +
{{MudletVersion|4.14}}
 +
 
 +
;Parameter
 +
* ''userName:''
 +
: The user name the event handler was registered under.s
 +
* ''handlerName:''
 +
: The name of the handler to resume. Same as used when you called [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]]
 +
 
 +
;Returns
 +
* true if successful, false if it didn't exist. If the timer is waiting to fire it will be restarted at 0.
 +
 
 +
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
0 = default text color
+
local resumed = resumeNamedTimer("Demonnic", "DemonVitals")
1 = light black
+
if resumed then
2 = dark black
+
  cecho("DemonVitals resumed!")
3 = light red
+
else
4 = dark red
+
  cecho("DemonVitals doesn't exist, so cannot resume it.")
5 = light green
+
end
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
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
;Examples
+
==setButtonState==
 +
;setButtonState(ButtonNameOrID, checked)
 +
:Sets the state of a check-able ("push-down") type button from any Mudlet item's script - but does not cause the script or one of the commands associated with that button to be run/sent.
 +
: See also: [[#getButtonState|getButtonState()]].
 +
{{MudletVersion|4.13}}
 +
 
 +
;Parameters
 +
* ''ButtonNameOrID:''
 +
: The name of the button as a string or a unique ID (positive) integer number {for a name only one matching one will be affected - it will be the same one that the matching [[#getButtonState|getButtonState()]] reports upon}.
 +
* ''checked:''
 +
: boolean value that indicated whether the state required is down (''true'') or up (''false'').
 +
 
 +
;Returns:
 +
* A boolean value indicating ''true'' if the visible state was actually changed, i.e. had any effect. This function will return a ''nil'' and a suitable error message if the identifying name or ID was not found or was not a check-able (push-down) button item (i.e. was a non-checkable button or a menu or a toolbar instead).
 +
 
 +
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- This script will re-highlight all text in blue foreground colors on a black background with a red foreground color
+
-- inside, for example, an initialization script for a GUI package:
-- on a blue background color until another color in the current line is being met. temporary color triggers do not
+
setButtonState("Sleep", false)
-- offer match_all or filter options like the GUI color triggers because this is rarely necessary for scripting.
+
setButtonState("Sit", false)
-- A common usage for temporary color triggers is to schedule actions on the basis of forthcoming text colors in a particular context.
+
-- these are going to be used as "radio" buttons where setting one
tempColorTrigger(9, 2, [[selectString(matches[1],1) fg("red") bg("blue")]])
+
-- of them will unset all the others, they will each need something
-- or:
+
-- similar in their own scripts to unset all the others in the set
tempColorTrigger(9, 2, function()
+
-- and also something to prevent them from being unset by clicking
  selectString(matches[1], 1)
+
-- on themselves:
  fg("red")
+
setButtonState("Wimpy", true)
  bg("blue")
+
setButtonState("Defensive", false)
end)
+
setButtonState("Normal", false)
 
+
setButtonState("Brave", false)
-- match the trigger only 4 times
+
if character.type == "Warrior" then
tempColorTrigger(9, 2, [[selectString(matches[1],1) fg("red") bg("blue")]], 4)
+
    -- Only one type has this mode - and it can only be reset by
 +
    -- something dying (though that could be us!)
 +
    setButtonState("Beserk!!!", false)
 +
end
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==tempComplexRegexTrigger==
+
==setConsoleBufferSize==
;tempComplexRegexTrigger(name, regex, code, multiline, fg color, bg color, filter, match all, highlight fg color, highlight bg color, play sound file, fire length, line delta, expireAfter)
+
;setConsoleBufferSize([consoleName], linesLimit, sizeOfBatchDeletion)
:Allows you to create a temporary trigger in Mudlet, using any of the UI-available options. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
+
:Sets the maximum number of lines a buffer (main window or a miniconsole) can hold. Default is 10,000.
:Returns the trigger name, that you can use [[Manual:Lua_Functions#killTrigger|killTrigger()]] later on with.
+
:Returns nothing on success (up to '''Mudlet 4.16''') or ''true'' (from '''Mudlet 4.17'''); ''nil'' and an error message on failure.
  
 
;Parameters
 
;Parameters
* ''name'' - The name you call this trigger.
+
* ''consoleName:''
* ''regex'' - The regular expression you want to match.
+
: (optional) The name of the window. If omitted, uses the main console.
* ''code'' - Code to do when the trigger runs. You need to wrap it in [[ ]], or give a Lua function (since Mudlet 3.5.0).
+
* ''linesLimit:''
* ''multiline'' - Set this to 1, if you use multiple regex (see note below), and you need the trigger to fire only if all regex have been matched within the specified line delta. Then all captures will be saved in ''multimatches'' instead of ''matches''. If this option is set to 0, the trigger will fire when any regex has been matched.
+
: Sets the amount of lines the buffer should have.  
* ''fg color'' - The foreground color you'd like to trigger on.
+
{{note}} Mudlet performs extremely efficiently with even huge numbers, but there is of course a limit to your computer's memory. As of Mudlet 4.7+, this amount will be capped to that limit on macOS and Linux (on Windows, it's capped lower as Mudlet on Windows is 32bit).
* ''bg color'' - The background color you'd like to trigger on.
+
* ''sizeOfBatchDeletion:''
* ''filter'' - Do you want only the filtered content (=capture groups) to be passed on to child triggers? Otherwise also the initial line.
+
: 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.
* ''match all'' - Set to 1, if you want the trigger to match all possible occurrences of the regex in the line. When set to 0, the trigger will stop after the first successful match.
 
* ''highlight fg color'' - The foreground color you'd like your match to be highlighted in.
 
* ''highlight bg color'' - The background color you'd like your match to be highlighted in.
 
* ''play sound file'' - Set to the name of the sound file you want to play upon firing the trigger.
 
* ''fire length'' - Number of lines within which all condition must be true to fire the trigger.
 
* ''line delta'' - Keep firing the script for x more lines, after the trigger or chain has matched.
 
* ''expireAfter'' - Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
 
  
{{Note}} Set the options starting at ''multiline'' to 0, if you don't want to use those options. Otherwise enter 1 to activate or the value you want to use.
+
;Example
 +
<syntaxhighlight lang="lua">
 +
-- sets the main windows size to 1 million lines maximum - which is more than enough!
 +
setConsoleBufferSize("main", 1000000, 1000)
 +
</syntaxhighlight>
  
{{Note}} If you want to use the color option, you need to provide both fg and bg together.
+
==setProfileIcon==
 +
;setProfileIcon(iconPath)
 +
:Set a custom icon for this profile in the connection screen.  
  
;Examples
+
:Returns true if successful, or nil+error message if not.
  
<syntaxhighlight lang="lua">
+
:See also: [[#resetProfileIcon|resetProfileIcon()]].
-- This trigger will be activated on any new line received.
 
triggerNumber = tempComplexRegexTrigger("anyText", "^(.*)$", [[echo("Text received!")]], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
 
  
-- This trigger will match two different regex patterns:
+
{{MudletVersion|4.0}}
tempComplexRegexTrigger("multiTrigger", "first regex pattern", [[]], 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
+
 
tempComplexRegexTrigger("multiTrigger", "second regex pattern", [[echo("Trigger matched!")]], 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
+
;Parameters
 +
* ''iconPath:''
 +
: Full location of the icon - can be .png or .jpg with ideal dimensions of 120x30.
 +
 
 +
;Example
 +
<syntaxhighlight lang="lua">
 +
-- set a custom icon that is located in an installed package called "mypackage"
 +
setProfileIcon(getMudletHomeDir().."/mypackage/icon.png")
 
</syntaxhighlight>
 
</syntaxhighlight>
  
{{Note}} For making a multiline trigger like in the second example, you need to use the same trigger name and options, providing the new pattern to add. Note that only the last script given will be set, any others ignored.
+
==setScript==
 +
;setScript(scriptName, luaCode, [occurrence])
 +
: Sets the script's Lua code, replacing existing code. If you have many scripts with the same name, use the 'occurrence' parameter to choose between them.
 +
: If you'd like to add code instead of replacing it, have a look at [[Manual:Lua_Functions#appendScript|appendScript()]].
 +
: Returns -1 if the script isn't found - to create a script, use [[Manual:Lua_Functions#permScript|permScript()]].
 +
 
 +
: See also: [[Manual:Lua_Functions#permScript|permScript()]], [[Manual:Lua_Functions#enableScript|enableScript()]], [[Manual:Lua_Functions#disableScript|disableScript()]], [[Manual:Lua_Functions#getScript|getScript()]], [[Manual:Lua_Functions#appendScript|appendScript()]]
  
==tempExactMatchTrigger==
+
;Returns
;tempExactMatchTrigger(exact line, code, expireAfter)
+
* a unique id number for that script.
:Creates a trigger that will go off whenever the line from the game matches the provided line exactly (ends the same, starts the same, and looks the same). You don't need to use any of the regex symbols here (^ and $). The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
 
  
 
;Parameters
 
;Parameters
* ''exact line'': exact line you'd like to match.
+
* ''scriptName'': name of the script to change the code.
* ''code'': code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5.0).
+
* ''luaCode'': new Lua code to set.
* ''expireAfter'': Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
+
* ''occurrence'': The position of the script. Optional, defaults to 1 (first).
  
;Examples
+
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
mytriggerID = tempExactMatchTrigger("You have recovered balance on all limbs.", [[echo("We matched!")]])
+
-- make sure a script named "testscript" exists first, then do:
 +
setScript("testscript", [[echo("This is a test\n")]], 1)
 +
</syntaxhighlight>
 +
{{MudletVersion|4.8}}
  
-- as a function:
+
==setStopWatchName==
mytriggerID = tempExactMatchTrigger("You have recovered balance on all limbs.", function() echo("We matched!") end)
+
;setStopWatchName(watchID/currentStopWatchName, newStopWatchName)
  
-- expire after 4 matches:
+
;Parameters
tempExactMatchTrigger("You have recovered balance on all limbs.", function() echo("Got balance back!\n") end, 4)
+
* ''watchID'' (number) / ''currentStopWatchName'' (string): The stopwatch ID you get from [[Manual:Lua_Functions#createStopWatch|createStopWatch()]] or the name supplied to that function at that time, or previously applied with this function.
 +
* ''newStopWatchName'' (string): The name to use for this stopwatch from now on.
  
-- you can also avoid expiration by returning true:
+
;Returns
tempExactMatchTrigger("You have recovered balance on all limbs.", function() echo("Got balance back!\n") return true end, 4)
+
* ''true'' on success, ''nil'' and an error message if no matching stopwatch is found.
</syntaxhighlight>
 
  
==tempKey==
+
{{note}} Either ''currentStopWatchName'' or ''newStopWatchName'' may be empty strings: if the first of these is so then the ''lowest'' ID numbered stopwatch without a name is chosen; if the second is so then an existing name is removed from the chosen stopwatch.
;tempKey([modifier], key code, lua code)
 
:Creates a keybinding. This keybinding isn't temporary in the sense that it'll go off only once (it'll go off as often as you use it), but rather it won't be saved when Mudlet is closed.
 
  
: See also: [[#permKey|permKey()]], [[#killKey|killKey()]]
+
==setStopWatchPersistence==
 +
;setStopWatchPersistence(watchID/watchName, state)
  
* ''modifier''  
+
;Parameters
:(optional) modifier to use - can be one of ''mudlet.keymodifier.Control'', ''mudlet.keymodifier.Alt'', ''mudlet.keymodifier.Shift'', ''mudlet.keymodifier.Meta'', ''mudlet.keymodifier.Keypad'', or ''mudlet.keymodifier.GroupSwitch'' or the default value of ''mudlet.keymodifier.None'' which is used if the argument is omitted. To use multiple modifiers, add them together: ''(mudlet.keymodifier.Shift + mudlet.keymodifier.Control)''
+
* ''watchID'' (number) / ''watchName'' (string): The stopwatch ID you get from [[Manual:Lua_Functions#createStopWatch|createStopWatch()]] or the name supplied to that function or applied later with [[Manual:Lua_Functions#setStopWatchName|setStopWatchName()]]
* ''key code''  
+
* ''state'' (boolean): if ''true'' the stopWatch will be saved.
: actual key to use - one of the values available in ''mudlet.key'', e.g. ''mudlet.key.Escape'', ''mudlet.key.Tab'', ''mudlet.key.F1'', ''mudlet.key.A'', and so on. The list is a bit long to list out in full so it is [https://github.com/Mudlet/Mudlet/blob/development/src/mudlet-lua/lua/KeyCodes.lua#L2 available here].
 
* ''lua code'
 
: code you'd like the key to run - wrap it in [[ ]].
 
  
 
;Returns
 
;Returns
* a unique id number for that key.
+
* ''true'' on success, ''nil'' and an error message if no matching stopwatch is found.
 +
 
 +
:Sets or resets the flag so that the stopwatch is saved between sessions or after a [[Manual:Miscellaneous_Functions#resetProfile|resetProfile()]] call. If set then, if ''stopped'' the elapsed time recorded will be unchanged when the stopwatch is reloaded in the next session; if ''running'' the elapsed time will continue to increment and it will include the time that the profile was not loaded, therefore it can be used to measure events in real-time, outside of the profile!
 +
 
 +
{{note}} When a persistent stopwatch is reloaded in a later session (or after a use of ''resetProfile()'') the stopwatch may not be allocated the same ID number as before - therefore it is advisable to assign any persistent stopwatches a name, either when it is created or before the session is ended.
 +
 
 +
==setTriggerStayOpen==
 +
;setTriggerStayOpen(name, number of lines)
 +
: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 of lines'': 0 to close the chain, or a positive number to keep the chain open that much longer.
  
 
;Examples
 
;Examples
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
local keyID = tempKey(mudlet.key.F8, [[echo("hi")]])
+
-- 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 prompt trigger inside the chain with a script of:
 +
setTriggerStayOpen("Parent trigger name", 0)
 +
-- to close it on the prompt!
 +
</syntaxhighlight>
  
local anotherKeyID = tempKey(mudlet.keymodifier.Control, mudlet.key.F8, [[echo("hello")]])
+
==startStopWatch==
 +
;startStopWatch(watchName or watchID, [resetAndRestart])
  
-- bind Ctrl+Shift+W:
+
:Stopwatches can be stopped (with [[Manual:Lua_Functions#stopStopWatch|stopStopWatch()]]) and then re-started any number of times. '''To ensure backwards compatibility, if the stopwatch is identified by a ''numeric'' argument then, ''unless a second argument of false is supplied as well'' this function will also reset the stopwatch to zero and restart it - whether it is running or not'''; otherwise only a stopped watch can be started and only a started watch may be stopped. Trying to repeat either will produce a nil and an error message instead; also the recorded time is no longer reset so that they can now be used to record a total of isolated periods of time like a real stopwatch.
tempKey(mudlet.keymodifier.Control + mudlet.keymodifier.Shift, mudlet.key.W, [[send("jump")]])
 
  
-- delete it if you don't like it anymore
+
:See also: [[Manual:Lua_Functions#createStopWatch|createStopWatch()]],  [[Manual:Lua_Functions#stopStopWatch|stopStopWatch()]]
killKey(keyID)
 
</syntaxhighlight>
 
  
==tempLineTrigger==
+
;Parameters
;tempLineTrigger(from, howMany, code, expireAfter)
+
* ''watchID''/''watchName'': The stopwatch ID you get with [[Manual:Lua_Functions#createStopWatch|createStopWatch()]], or from '''4.4.0''' the name assigned with that function or [[Manual:Lua_Functions#setStopWatchName|setStopWatchName()]].
:Temporary trigger that will fire on ''n'' consecutive lines following the current line. This is useful to parse output that is known to arrive in a certain line margin or to delete unwanted output from the MUD - the trigger does not require any patterns to match on. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
+
* ''resetAndRestart'': Boolean flag needed (as ''false'') to make the function from '''4.4.0''', when supplied with a numeric watch ID, to '''not''' reset the stopwatch and only start a previously stopped stopwatch. This behavior is automatic when a string watch name is used to identify the stopwatch but differs from how the function behaved prior to that version.
  
;Parameters:
+
;Returns
* ''from'': from which line after this one should the trigger activate - 1 will activate right on the next line.
+
* ''true'' on success, ''nil'' and an error message if no matching stopwatch is found or if it cannot be started (because the later style behavior was indicated and it was already running).
* ''howMany'': how many lines to run for after the trigger has activated.
 
* ''code'': code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5.0).
 
* ''expireAfter'': Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
 
  
;Example:
+
;Examples
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- Will fire 3 times with the next line from the MUD.
+
-- this is a common pattern for re-using stopwatches prior to 4.4.0 and starting them:
tempLineTrigger(1, 3, function() print(" trigger matched!") end)
+
watch = watch or createStopWatch()
 +
startStopWatch(watch)
 +
</syntaxhighlight>
  
-- Will fire 20 lines after the current line and fire twice on 2 consecutive lines, 7 times.
+
:: After 4.4.0 the above code will work the same as it does not provide a second argument to the ''startStopWatch()'' function - if a ''false'' was used there it would be necessary to call ''stopStopWatch(...)'' and then ''resetStopWatch(...)'' before using ''startStopWatch(...)'' to re-use the stopwatch if the ID form is used, '''this is thus not quite the same behavior but it is more consistent with the model of how a real stopwatch would act.'''
tempLineTrigger(20, 2, function() print(" trigger matched!") end, 7)
 
</syntaxhighlight>
 
  
==tempPromptTrigger==
+
==stopAllNamedTimers==
;tempPromptTrigger(code, expireAfter)
+
; stopAllNamedTimers(userName)
:Temporary trigger that will match on the games prompt. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
 
  
{{note}} If the trigger is not working, check that the '''N:''' bottom-right has a number. This feature requires telnet Go-Ahead to be enabled in the game. Available in Mudlet 3.6+
+
:Stops all named timers for userName and prevents them from firing any more. Information is retained and timers can be resumed.
  
;Parameters:
+
;See also: [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]], [[Manual:Lua_Functions#stopNamedTimer|stopNamedTimer()]], [[Manual:Lua_Functions#resumeNamedTimer|resumeNamedTimer()]]
* ''code'': code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function.
 
* ''expireAfter'': Delete trigger after a specified number of matches. You can make a trigger match not count towards expiration by returning true after it fires.
 
  
{{note}} ''expireAfter'' is available since Mudlet 3.11
+
{{MudletVersion|4.14}}
  
;Example:
+
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
tempPromptTrigger(function()
+
stopAllNamedTimers("Demonnic") -- emergency stop situation, most likely.
  echo("hello! this is a prompt!")
+
</syntaxhighlight>
end)
+
 
 +
==stopNamedTimer==
 +
; success = stopNamedTimer(userName, handlerName)
 +
 
 +
:Stops a named timer with name handlerName and prevents it from firing any more. Information is stored so it can be resumed later if desired.
  
-- match only 2 times:
+
;See also: [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]], [[Manual:Lua_Functions#resumeNamedTimer|resumeNamedTimer()]]
tempPromptTrigger(function()
 
  echo("hello! this is a prompt!")
 
end, 2)
 
  
-- match only 2 times, unless the prompt is "55 health."
+
{{MudletVersion|4.14}}
tempPromptTrigger(function()
 
  if line == "55 health." then return true end
 
end, 2)
 
</syntaxhighlight>
 
  
==tempRegexTrigger==
+
;Parameters
;tempRegexTrigger(regex, code, expireAfter)
+
* ''userName:''
:Creates a temporary regex trigger that executes the code whenever it matches. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
+
: The user name the event handler was registered under.
 +
* ''handlerName:''
 +
: The name of the handler to stop. Same as used when you called [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]]
  
;Parameters:
+
;Returns
* ''regex:'' regular expression that lines will be matched on.
+
* true if successful, false if it didn't exist or was already stopped
* ''code'': code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5.0).
 
* ''expireAfter'': Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
 
  
;Examples:
+
;Example
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- create a non-duplicate trigger that matches on any line and calls a function
+
local stopped = stopNamedTimer("Demonnic", "DemonVitals")
html5log = html5log or {}
+
if stopped then
if html5log.trig then killTrigger(html5log.trig) end
+
  cecho("DemonVitals stopped!")
html5log.trig = tempRegexTrigger("^", [[html5log.recordline()]])
+
else
-- or a simpler variant:
+
  cecho("DemonVitals doesn't exist or already stopped; either way it won't fire any more.")
html5log.trig = tempRegexTrigger("^", html5log.recordline)
+
end
 +
</syntaxhighlight>
 +
 
 +
==stopStopWatch==
 +
;stopStopWatch(watchID or watchName)
 +
:"Stops" (though see the note below) the stop watch and returns (only the '''first''' time it is called after the stopwatch has been set running with [[Manual:Lua_Functions#startStopWatch|startStopWatch()]]) the elapsed time as a number of seconds, with a decimal portion give a resolution in milliseconds (thousandths of a second). You can also retrieve the current time without stopping the stopwatch with [[Manual:Lua_Functions#getStopWatchTime|getStopWatchTime()]], [[Manual:Lua_Functions#getBrokenDownStopWatchTime|getBrokenDownStopWatchTime()]].
  
-- only match 3 times:
+
:See also: [[Manual:Lua_Functions#createStopWatch|createStopWatch()]]
tempRegexTrigger("^You prick (.+) twice in rapid succession with", function() echo("Hit "..matches[2].."!\n") end, 3)
 
</syntaxhighlight>
 
  
==tempTimer==
+
;Parameters
;tempTimer(time, code to do[, repeating])
+
* ''watchID:'' The stopwatch ID you get with [[Manual:Lua_Functions#createStopWatch|createStopWatch()]] or from Mudlet '''4.4.0''' the name given to that function or later set with [[Manual:Lua_Functions#setStopWatchName|setStopWatchName()]].
:Creates a temporary one-shot timer and returns the timer ID, which you can use with [[Manual:Lua_Functions#enableTimer|enableTimer()]], [[Manual:Lua_Functions#disableTimer|disableTimer()]] and [[Manual:Lua_Functions#killTimer|killTimer()]] functions. You can use 2.3 seconds or 0.45 etc. After it has fired, the timer will be deactivated and destroyed, so it will only go off once. Here is a [[Manual:Introduction#Timers|more detailed introduction to tempTimer]].
 
  
;Parameters
+
;Returns
* ''time:'' The time in seconds for which to set the timer for - you can use decimals here for precision. The timer will go off ''x'' given seconds after you make it.
+
* the elapsed time as a floating-point number of seconds - it may be negative if the time was previously adjusted/preset to a negative amount (with [[Manual:Lua_Functions#adjustStopWatch|adjustStopWatch()]]) and that period has not yet elapsed.
* ''code to do'': The code to do when the timer is up - wrap it in [[ ]], or provide a Lua function.
 
* ''repeating'': (optional) if true, keep firing the timer over and over until you kill it (available in Mudlet 4.0+).
 
  
 
;Examples
 
;Examples
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- wait half a second and then run the command
+
-- this is a common pattern for re-using stopwatches and starting them:
tempTimer(0.5, function() send("kill monster") end)
+
watch = watch or createStopWatch()
 +
startStopWatch(watch)
 +
 
 +
-- do some long-running code here ...
  
-- or an another example - two ways to 'embed' variable in a code for later:
+
print("The code took: "..stopStopWatch(watch).."s to run.")
local name = matches[2]
 
tempTimer(2, [[send("hello, ]]..name..[[ !")]])
 
-- or:
 
tempTimer(2, function()
 
  send("hello, "..name)
 
end)
 
 
 
-- create a looping timer
 
timerid = tempTimer(1, function() display("hello!") end, true)
 
 
 
-- later when you'd like to stop it:
 
killTimer(timerid)
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
{{note}} Double brackets, e.g: [[ ]] can be used to quote strings in Lua. The difference to the usual `" " quote syntax is that `[[ ]] also accepts the character ". Consequently, you don’t have to escape the " character in the above script. The other advantage is that it can be used as a multiline quote, so your script can span several lines.
+
==tempAnsiColorTrigger==
 +
;tempAnsiColorTrigger(foregroundColor[, backgroundColor], code[, expireAfter])
 +
:This is an alternative to [[Manual:Lua_Functions#tempColorTrigger|tempColorTrigger()]] which supports the full set of 256 ANSI color codes directly and makes a color trigger that triggers on the specified foreground and background color. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
  
{{note}} Lua code that you provide as an argument is compiled from a string value when the timer fires. This means that if you want to pass any parameters by value e.g. you want to make a function call that uses the value of your variable myGold as a parameter you have to do things like this:
+
;Parameters
 +
* ''foregroundColor:'' The foreground color you'd like to trigger on.
 +
* ''backgroundColor'': The background color you'd like to trigger on.
 +
* ''code to do'': The code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function.
 +
* ''expireAfter'': Delete trigger after a specified number of matches. You can make a trigger match not count towards expiration by returning true after it fires.
  
<syntaxhighlight lang="lua">
+
''BackgroundColor'' and/or ''expireAfter'' may be omitted.
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:
+
;Color codes (note that the values greater than or equal to zero are the actual number codes that ANSI and the game server uses for the 8/16/256 color modes)
  
local variable = matches[2]
+
::Special codes (may be extended in the future):
tempTimer(3, function () send("hello, " .. variable) end)
+
:::-2 = default text color (what is used after an ANSI SGR 0 m code that resets the foreground and background colors to those set in the preferences)
</syntaxhighlight>
+
:::-1 = ignore (only '''one''' of the foreground or background codes can have this value - otherwise it would not be a ''color'' trigger!)
  
==tempTrigger==
+
::ANSI 8-color set:
;tempTrigger(substring, code, expireAfter)
+
:::0 = (dark) black
:Creates a substring trigger that executes the code whenever it matches. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
+
:::1 = (dark) red
 +
:::2 = (dark) green
 +
:::3 = (dark) yellow
 +
:::4 = (dark) blue
 +
:::5 = (dark) magenta
 +
:::6 = (dark) cyan
 +
:::7 = (dark) white {a.k.a. light gray}
  
;Parameters:
+
::Additional colors in 16-color set:
* ''substring'': The substring to look for - this means a part of the line. If your provided text matches anywhere within the line from the game, the trigger will go off.
+
:::8 = light black {a.k.a. dark gray}
* ''code'': The code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5)
+
:::9 = light red
* ''expireAfter'': Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
+
:::10 = light green
 +
:::11 = light yellow
 +
:::12 = light blue
 +
:::13 = light magenta
 +
:::14 = light cyan
 +
:::15 = light white
 +
 
 +
::6 x 6 x 6 RGB (216) colors, shown as a 3x2-digit hex code
 +
:::16 = #000000
 +
:::17 = #000033
 +
:::18 = #000066
 +
:::...
 +
:::229 = #FFFF99
 +
:::230 = #FFFFCC
 +
:::231 = #FFFFFF
  
Example:
+
::24 gray-scale, also show as a 3x2-digit hex code
 +
:::232 = #000000
 +
:::233 = #0A0A0A
 +
:::234 = #151515
 +
:::...
 +
:::253 = #E9E9E9
 +
:::254 = #F4F4F4
 +
:::255 = #FFFFFF
 +
 
 +
;Examples
 
<syntaxhighlight lang="lua">
 
<syntaxhighlight lang="lua">
-- this example will highlight the contents of the "target" variable.
+
-- This script will re-highlight all text in a light cyan foreground color on any background with a red foreground color
-- it will also delete the previous trigger it made when you call it again, so you're only ever highlighting one name
+
-- until another foreground 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.
 +
tempAnsiColorTrigger(14, -1, [[selectString(matches[1],1) fg("red")]])
 +
-- or:
 +
tempAnsiColorTrigger(14, -1, function()
 +
  selectString(matches[1], 1)
 +
  fg("red")
 +
end)
 +
 
 +
-- match the trigger only 4 times
 +
tempColorTrigger(14, -1, [[selectString(matches[1],1) fg("red")]], 4)
 +
</syntaxhighlight>
 +
 
 +
{{MudletVersion|3.17}}
 +
 
 +
==tempAlias==
 +
;aliasID = tempAlias(regex, code to do)
 +
:Creates a temporary alias - temporary in the sense that it won't be saved when Mudlet restarts (unless you re-create it). The alias will go off as many times as it matches, it is not a one-shot alias. The function returns an ID for subsequent [[Manual:Lua_Functions#enableAlias|enableAlias()]], [[Manual:Lua_Functions#disableAlias|disableAlias()]] and [[Manual:Lua_Functions#killAlias|killAlias()]] calls.
 +
 
 +
;Parameters
 +
* ''regex:'' Alias pattern in regex.
 +
* ''code to do:'' The code to do when the alias fires - wrap it in [[ ]].
 +
 
 +
;Examples
 +
<syntaxhighlight lang="lua">
 +
myaliasID = tempAlias("^hi$", [[send ("hi") echo ("we said hi!")]])
 +
 
 +
-- you can also delete the alias later with:
 +
killAlias(myaliasID)
 +
 
 +
-- tempAlias also accepts functions (and thus closures) - which can be an easier way to embed variables and make the code for an alias look less messy:
 +
 
 +
local variable = matches[2]
 +
tempAlias("^hi$", function () send("hello, " .. variable) end)
 +
</syntaxhighlight>
 +
 
 +
==tempBeginOfLineTrigger==
 +
;tempBeginOfLineTrigger(part of line, code, expireAfter)
 +
:Creates a trigger that will go off whenever the part of line it's provided with matches the line right from the start (doesn't matter what the line ends with). The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls.
 +
 
 +
;Parameters
 +
* ''part of line'': start of the line that you'd like to match. This can also be regex.
 +
* ''code to do'': code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5.0).
 +
* ''expireAfter'': Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
 +
 
 +
;Examples
 +
<syntaxhighlight lang="lua">
 +
mytriggerID = tempBeginOfLineTrigger("Hello", [[echo("We matched!")]])
 +
 
 +
--[[ now this trigger will match on any of these lines:
 +
Hello
 +
Hello!
 +
Hello, Bob!
 +
 
 +
but not on:
 +
Oh, Hello
 +
Oh, Hello!
 +
]]
 +
 
 +
-- or as a function:
 +
mytriggerID = tempBeginOfLineTrigger("Hello", function() echo("We matched!") end)
 +
</syntaxhighlight>
 +
 
 +
<syntaxhighlight lang="lua">
 +
-- you can make the trigger match only a certain amount of times as well, 5 in this example:
 +
tempBeginOfLineTrigger("This is the start of the line", function() echo("We matched!") end, 5)
 +
 
 +
-- if you want a trigger match not to count towards expiration, return true. In this example it'll match 5 times unless the line is "Start of line and this is the end."
 +
tempBeginOfLineTrigger("Start of line",
 +
function()
 +
  if line == "Start of line and this is the end." then
 +
    return true
 +
  else
 +
    return false
 +
  end
 +
end, 5)
 +
</syntaxhighlight>
 +
 
 +
==tempButton==
 +
;tempButton(toolbar name, button text, orientation)
 +
:Creates a temporary button. Temporary means, it will disappear when Mudlet is closed.
 +
 
 +
;Parameters:
 +
* ''toolbar name'': The name of the toolbar to place the button into.
 +
* ''button text'': The text to display on the button.
 +
* ''orientation'': a number 0 or 1 where 0 means horizontal orientation for the button and 1 means vertical orientation for the button. This becomes important when you want to have more than one button in the same toolbar.
 +
 
 +
;Example
 +
<syntaxhighlight lang="lua">
 +
-- makes a temporary toolbar with two buttons at the top of the main Mudlet window
 +
lua tempButtonToolbar("topToolbar", 0, 0)
 +
lua tempButton("topToolbar", "leftButton", 0)
 +
lua tempButton("topToolbar", "rightButton", 0)
 +
</syntaxhighlight>
 +
 
 +
{{note}} ''This function is not that useful as there is no function yet to assign a Lua script or command to such a temporary button - though it may have some use to flag a status indication!''
 +
 
 +
==tempButtonToolbar==
 +
;tempButtonToolbar(name, location, orientation)
 +
:Creates a temporary button toolbar. Temporary means, it will disappear when Mudlet is closed.
 +
 
 +
;Parameters:
 +
* ''name'': The name of the toolbar.
 +
* ''location'': a number from 0 to 3, where 0 means "at the top of the screen", 1 means "left side", 2 means "right side" and 3 means "in a window of its own" which can be dragged and attached to the main Mudlet window if needed.
 +
* ''orientation'': a number 0 or 1, where 0 means horizontal orientation for the toolbar and 1 means vertical orientation for the toolbar. This becomes important when you want to have more than one toolbar in the same location of the window.
 +
 
 +
;Example
 +
<syntaxhighlight lang="lua">
 +
-- makes a temporary toolbar with two buttons at the top of the main Mudlet window
 +
lua tempButtonToolbar("topToolbar", 0, 0)
 +
lua tempButton("topToolbar", "leftButton", 0)
 +
lua tempButton("topToolbar", "rightButton", 0)
 +
</syntaxhighlight>
 +
 
 +
==tempColorTrigger==
 +
;tempColorTrigger(foregroundColor, backgroundColor, code, expireAfter)
 +
:Makes a color trigger that triggers on the specified foreground and background color. Both colors need to be supplied in form of these simplified ANSI 16 color mode codes. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
 +
See also: [[Manual:Mudlet Object Functions#tempAnsiColorTrigger|tempAnsiColorTrigger]]
 +
;Parameters
 +
* ''foregroundColor:'' The foreground color you'd like to trigger on (for ANSI colors, see [[Manual:Mudlet Object Functions#tempAnsiColorTrigger|tempAnsiColorTrigger]]).
 +
* ''backgroundColor'': The background color you'd like to trigger on (same as above).
 +
* ''code to do'': The code to do when the trigger runs - wrap it in <code>[[</code> and <code>]]</code>, or give it a Lua function, ie. <code>function() <nowiki><your code here></nowiki> end</code> (since Mudlet 3.5.0).
 +
* ''expireAfter'': Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
 +
 
 +
;Color codes
 +
<syntaxhighlight lang="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
 +
</syntaxhighlight>
 +
 
 +
;Examples
 +
<syntaxhighlight lang="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")]])
 +
-- or:
 +
tempColorTrigger(9, 2, function()
 +
  selectString(matches[1], 1)
 +
  fg("red")
 +
  bg("blue")
 +
end)
 +
 
 +
-- match the trigger only 4 times
 +
tempColorTrigger(9, 2, [[selectString(matches[1],1) fg("red") bg("blue")]], 4)
 +
</syntaxhighlight>
 +
 
 +
==tempComplexRegexTrigger==
 +
;tempComplexRegexTrigger(name, regex, code, multiline, fg color, bg color, filter, match all, highlight fg color, highlight bg color, play sound file, fire length, line delta, expireAfter)
 +
:Allows you to create a temporary trigger in Mudlet, using any of the UI-available options. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
 +
:Returns the trigger ID or nil and an error message (on error).
 +
 
 +
;Parameters
 +
* ''name'' - The name you call this trigger. You can use this with [[Manual:Lua_Functions#killTrigger|killTrigger()]].
 +
* ''regex'' - The regular expression you want to match.
 +
* ''code'' - Code to do when the trigger runs. You need to wrap it in [[ ]], or give a Lua function (since Mudlet 3.5.0).
 +
* ''multiline'' - Set this to 1, if you use multiple regex (see note below), and you need the trigger to fire only if all regex have been matched within the specified line delta. Then all captures will be saved in ''multimatches'' instead of ''matches''. If this option is set to 0, the trigger will fire when any regex has been matched.
 +
* ''fg color'' - The foreground color you'd like to trigger on - '''Not currently implemented.'''
 +
* ''bg color'' - The background color you'd like to trigger on - '''Not currently implemented.'''
 +
* ''filter'' - Do you want only the filtered content (=capture groups) to be passed on to child triggers? Otherwise also the initial line.
 +
* ''match all'' - Set to 1, if you want the trigger to match all possible occurrences of the regex in the line. When set to 0, the trigger will stop after the first successful match.
 +
* ''highlight fg color'' - The foreground color you'd like your match to be highlighted in. e.g. <code>"yellow"</code>, <code>"#ff0"</code> or <code>"#ffff00"</code>
 +
* ''highlight bg color'' - The background color you'd like your match to be highlighted in. e.g. <code>"red"</code>, <code>"#f00"</code> or <code>"#ff0000"</code>
 +
* ''play sound file'' - Set to the name of the sound file you want to play upon firing the trigger. e.g. <code>"C:/windows/media/chord.wav"</code>
 +
* ''fire length'' - Number of lines within which all condition must be true to fire the trigger.
 +
* ''line delta'' - Keep firing the script for x more lines, after the trigger or chain has matched.
 +
* ''expireAfter'' - Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
 +
 
 +
{{Note}} Set the options starting at ''multiline'' to 0, if you don't want to use those options. Otherwise enter 1 to activate or the value you want to use.
 +
 
 +
{{Note}} If you want to use the color option, you need to provide both fg and bg together. - '''Not currently implemented.'''
 +
 
 +
;Examples
 +
 
 +
<syntaxhighlight lang="lua">
 +
-- This trigger will be activated on any new line received.
 +
triggerNumber = tempComplexRegexTrigger("anyText", "^(.*)$", [[echo("Text received!")]], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, nil)
 +
 
 +
-- This trigger will match two different regex patterns:
 +
tempComplexRegexTrigger("multiTrigger", "first regex pattern", [[]], 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, nil)
 +
tempComplexRegexTrigger("multiTrigger", "second regex pattern", [[echo("Trigger matched!")]], 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, nil)
 +
</syntaxhighlight>
 +
 
 +
{{Note}} For making a multiline trigger like in the second example, you need to use the same trigger name and options, providing the new pattern to add. Note that only the last script given will be set, any others ignored.
 +
 
 +
==tempExactMatchTrigger==
 +
;tempExactMatchTrigger(exact line, code, expireAfter)
 +
:Creates a trigger that will go off whenever the line from the game matches the provided line exactly (ends the same, starts the same, and looks the same). You don't need to use any of the regex symbols here (^ and $). The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
 +
 
 +
;Parameters
 +
* ''exact line'': exact line you'd like to match.
 +
* ''code'': code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5.0).
 +
* ''expireAfter'': Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
 +
 
 +
;Examples
 +
<syntaxhighlight lang="lua">
 +
mytriggerID = tempExactMatchTrigger("You have recovered balance on all limbs.", [[echo("We matched!")]])
 +
 
 +
-- as a function:
 +
mytriggerID = tempExactMatchTrigger("You have recovered balance on all limbs.", function() echo("We matched!") end)
 +
 
 +
-- expire after 4 matches:
 +
tempExactMatchTrigger("You have recovered balance on all limbs.", function() echo("Got balance back!\n") end, 4)
 +
 
 +
-- you can also avoid expiration by returning true:
 +
tempExactMatchTrigger("You have recovered balance on all limbs.", function() echo("Got balance back!\n") return true end, 4)
 +
</syntaxhighlight>
 +
 
 +
==tempKey==
 +
;tempKey([modifier], key code, lua code)
 +
:Creates a keybinding. This keybinding isn't temporary in the sense that it'll go off only once (it'll go off as often as you use it), but rather it won't be saved when Mudlet is closed.
 +
 
 +
: See also: [[#permKey|permKey()]], [[#killKey|killKey()]]
 +
 
 +
* ''modifier''
 +
:(optional) modifier to use - can be one of ''mudlet.keymodifier.Control'', ''mudlet.keymodifier.Alt'', ''mudlet.keymodifier.Shift'', ''mudlet.keymodifier.Meta'', ''mudlet.keymodifier.Keypad'', or ''mudlet.keymodifier.GroupSwitch'' or the default value of ''mudlet.keymodifier.None'' which is used if the argument is omitted. To use multiple modifiers, add them together: ''(mudlet.keymodifier.Shift + mudlet.keymodifier.Control)''
 +
* ''key code''
 +
: actual key to use - one of the values available in ''mudlet.key'', e.g. ''mudlet.key.Escape'', ''mudlet.key.Tab'', ''mudlet.key.F1'', ''mudlet.key.A'', and so on. The list is a bit long to list out in full so it is [https://github.com/Mudlet/Mudlet/blob/development/src/mudlet-lua/lua/KeyCodes.lua#L2 available here].
 +
* ''lua code'
 +
: code you'd like the key to run - wrap it in [[ ]].
 +
 
 +
;Returns
 +
* a unique id number for that key.
 +
 
 +
;Examples
 +
<syntaxhighlight lang="lua">
 +
keyID = tempKey(mudlet.key.F8, [[echo("hi")]])
 +
 
 +
anotherKeyID = tempKey(mudlet.keymodifier.Control, mudlet.key.F8, [[echo("hello")]])
 +
 
 +
-- bind Ctrl+Shift+W:
 +
tempKey(mudlet.keymodifier.Control + mudlet.keymodifier.Shift, mudlet.key.W, [[send("jump")]])
 +
 
 +
-- delete it if you don't like it anymore
 +
killKey(keyID)
 +
 
 +
-- tempKey also accepts functions (and thus closures) - which can be an easier way to embed variables and make the code for tempKeys look less messy:
 +
 
 +
tempKey(mudlet.key.F8, function() echo("Hi\n") end)
 +
</syntaxhighlight>
 +
 
 +
==tempLineTrigger==
 +
;tempLineTrigger(from, howMany, code)
 +
:Temporary trigger that will fire on ''n'' consecutive lines following the current line. This is useful to parse output that is known to arrive in a certain line margin or to delete unwanted output from the game - the trigger does not require any patterns to match on. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
 +
 
 +
;Parameters:
 +
* ''from'': from which line after this one should the trigger activate - 1 will activate right on the next line.
 +
* ''howMany'': how many lines to run for after the trigger has activated.
 +
* ''code'': code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5.0).
 +
 
 +
;Example:
 +
<syntaxhighlight lang="lua">
 +
-- Will fire 3 times with the next line from the game
 +
tempLineTrigger(1, 3, function() print(" trigger matched!") end)
 +
 
 +
-- Will fire 5 lines after the current line and fire twice on 2 consecutive lines
 +
tempLineTrigger(5, 2, function() print(" trigger matched!") end, 7)
 +
</syntaxhighlight>
 +
 
 +
==tempPromptTrigger==
 +
;tempPromptTrigger(code, expireAfter)
 +
:Temporary trigger that will match on the games prompt. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
 +
 
 +
{{note}} If the trigger is not working, check that the '''N:''' bottom-right has a number. This feature requires telnet Go-Ahead to be enabled in the game.
 +
 
 +
{{MudletVersion|3.6}}
 +
 
 +
;Parameters:
 +
* ''code'':
 +
: code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function.
 +
* ''expireAfter'': (available in Mudlet 3.11+)
 +
: Delete trigger after a specified number of matches. You can make a trigger match not count towards expiration by returning true after it fires.
 +
 
 +
;Example:
 +
<syntaxhighlight lang="lua">
 +
tempPromptTrigger(function()
 +
  echo("hello! this is a prompt!")
 +
end)
 +
 
 +
-- match only 2 times:
 +
tempPromptTrigger(function()
 +
  echo("hello! this is a prompt!")
 +
end, 2)
 +
 
 +
-- match only 2 times, unless the prompt is "55 health."
 +
tempPromptTrigger(function()
 +
  if line == "55 health." then return true end
 +
end, 2)
 +
</syntaxhighlight>
 +
 
 +
==tempRegexTrigger==
 +
;tempRegexTrigger(regex, code, expireAfter)
 +
:Creates a temporary regex trigger that executes the code whenever it matches. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
 +
 
 +
;Parameters:
 +
* ''regex:'' regular expression that lines will be matched on.
 +
* ''code'': code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5.0).
 +
* ''expireAfter'': Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
 +
 
 +
;Examples:
 +
<syntaxhighlight lang="lua">
 +
-- create a non-duplicate trigger that matches on any line and calls a function
 +
html5log = html5log or {}
 +
if html5log.trig then killTrigger(html5log.trig) end
 +
html5log.trig = tempRegexTrigger("^", [[html5log.recordline()]])
 +
-- or a simpler variant:
 +
html5log.trig = tempRegexTrigger("^", html5log.recordline)
 +
 
 +
-- only match 3 times:
 +
tempRegexTrigger("^You prick (.+) twice in rapid succession with", function() echo("Hit "..matches[2].."!\n") end, 3)
 +
 
 +
-- since Mudlet 4.11+ you can use named capturing groups
 +
tempRegexTrigger("^You see (?<material>\\w+) axe inside chest\\.", function() echo("\nAxe is " .. matches.material) end)
 +
</syntaxhighlight>
 +
 
 +
==tempTimer==
 +
;tempTimer(time, code to do[, repeating])
 +
:Creates a temporary one-shot timer and returns the timer ID, which you can use with [[Manual:Lua_Functions#enableTimer|enableTimer()]], [[Manual:Lua_Functions#disableTimer|disableTimer()]] and [[Manual:Lua_Functions#killTimer|killTimer()]] functions. You can use 2.3 seconds or 0.45 etc. After it has fired, the timer will be deactivated and destroyed, so it will only go off once. Here is a [[Manual:Introduction#Timers|more detailed introduction to tempTimer]].
 +
 
 +
;Parameters
 +
* ''time:'' The time in seconds for which to set the timer for - you can use decimals here for precision. The timer will go off ''x'' given seconds after you make it.
 +
* ''code to do'': The code to do when the timer is up - wrap it in [[ ]], or provide a Lua function.
 +
* ''repeating'': (optional) if true, keep firing the timer over and over until you kill it (available in Mudlet 4.0+).
 +
 
 +
;Examples
 +
<syntaxhighlight lang="lua">
 +
-- wait half a second and then run the command
 +
tempTimer(0.5, function() send("kill monster") end)
 +
 
 +
-- echo between 1 and 5 seconds after creation
 +
tempTimer(math.random(1, 5), function() echo("hi!") end)
 +
 
 +
-- 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)
 +
 
 +
-- create a looping timer
 +
timerid = tempTimer(1, function() display("hello!") end, true)
 +
 
 +
-- later when you'd like to stop it:
 +
killTimer(timerid)
 +
</syntaxhighlight>
 +
 
 +
{{note}} Double brackets, e.g: [[ ]] can be used to quote strings in Lua. The difference to the usual `" " quote syntax is that `[[ ]] also accepts the character ". Consequently, you don’t have to escape the " character in the above script. The other advantage is that it can be used as a multiline quote, so your script can span several lines.
 +
 
 +
{{note}} 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:
 +
 
 +
<syntaxhighlight lang="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)
 +
</syntaxhighlight>
 +
 
 +
==tempTrigger==
 +
;tempTrigger(substring, code, expireAfter)
 +
:Creates a substring trigger that executes the code whenever it matches. The function returns the trigger ID for subsequent [[Manual:Lua_Functions#enableTrigger|enableTrigger()]], [[Manual:Lua_Functions#disableTrigger|disableTrigger()]] and [[Manual:Lua_Functions#killTrigger|killTrigger()]] calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the ''expireAfter'' parameter.
 +
 
 +
;Parameters:
 +
* ''substring'': The substring to look for - this means a part of the line. If your provided text matches anywhere within the line from the game, the trigger will go off.
 +
* ''code'': The code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5)
 +
* ''expireAfter'': Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
 +
 
 +
Example:
 +
<syntaxhighlight lang="lua">
 +
-- this example will highlight the contents of the "target" variable.
 +
-- it will also delete the previous trigger it made when you call it again, so you're only ever highlighting one name
 
if id then killTrigger(id) end
 
if id then killTrigger(id) end
id = tempTrigger(target, [[selectString("]] .. target .. [[", 1) fg("gold") resetFormat()]])
+
id = tempTrigger(target, [[selectString("]] .. target .. [[", 1) fg("gold") resetFormat()]])
 
+
 
-- you can also write the same line as:
+
-- you can also write the same line as:
id = tempTrigger(target, function() selectString(target, 1) fg("gold") resetFormat() end)
+
id = tempTrigger(target, function() selectString(target, 1) fg("gold") resetFormat() end)
 
+
 
-- or like so if you have a highlightTarget() function somewhere
+
-- or like so if you have a highlightTarget() function somewhere
id = tempTrigger(target, highlightTarget)
+
id = tempTrigger(target, highlightTarget)
 +
</syntaxhighlight>
 +
 
 +
<syntaxhighlight lang="lua">
 +
-- a simpler trigger to replace "hi" with "bye" whenever you see it
 +
tempTrigger("hi", [[selectString("hi", 1) replace("bye")]])
 +
</syntaxhighlight>
 +
 
 +
<syntaxhighlight lang="lua">
 +
-- this trigger will go off only 2 times
 +
tempTrigger("hi", function() selectString("hi", 1) replace("bye") end, 2)
 +
</syntaxhighlight>
 +
 
 +
<syntaxhighlight lang="lua">
 +
-- table to store our trigger IDs in
 +
nameIDs = nameIDs or {}
 +
-- delete any existing triggers we've already got
 +
for _, id in ipairs(nameIDs) do killTrigger(id) end
 +
 
 +
-- create new ones, avoiding lots of ]] [[ to embed the name
 +
for _, name in ipairs{"Alice", "Ashley", "Aaron"} do
 +
  nameIDs[#nameIDs+1] = tempTrigger(name, function() print(" Found "..name.."!") end)
 +
end
 
</syntaxhighlight>
 
</syntaxhighlight>
  
<syntaxhighlight lang="lua">
+
;Additional Notes:
-- a simpler trigger to replace "hi" with "bye" whenever you see it
+
tempTriggers begin matching on the same line they're created on.
tempTrigger("hi", [[selectString("hi", 1) replace("bye")]])
 
</syntaxhighlight>
 
 
 
<syntaxhighlight lang="lua">
 
-- this trigger will go off only 2 times
 
tempTrigger("hi", function() selectString("hi", 1) replace("bye") end, 2)
 
</syntaxhighlight>
 
  
<syntaxhighlight lang="lua">
+
If your ''code'' deletes and recreates the tempTrigger, or if you ''send'' a matching command again, it's possible to get into an infinite loop.
-- table to store our trigger IDs in
 
nameIDs = nameIDs or {}
 
-- delete any existing triggers we've already got
 
for _, id in ipairs(nameIDs) do killTrigger(id) end
 
  
-- create new ones, avoiding lots of ]] [[ to embed the name
+
Make use of the ''expireAfter'' parameter, [[Manual:Lua_Functions#disableTrigger|disableTrigger()]], or [[Manual:Lua_Functions#killTrigger|killTrigger()]] to prevent a loop from forming.
for _, name in ipairs{"Alice", "Ashley", "Aaron"} do
 
  nameIDs[#nameIDs+1] = tempTrigger(name, function() print(" Found "..name.."!") end)
 
end
 
</syntaxhighlight>
 
  
 
[[Category:Mudlet Manual]]
 
[[Category:Mudlet Manual]]
 
[[Category:Mudlet API]]
 
[[Category:Mudlet API]]

Latest revision as of 20:15, 4 November 2024

Mudlet Object Functions

Collection of functions to manipulate Mudlet's scripting objects - triggers, aliases, and so forth.

addCmdLineSuggestion

addCmdLineSuggestion([name], suggestion)
Add suggestion for tab completion for specified command line.
For example, start typing he and hit TAB until help appears in command line.
Non-word characters are skipped (this is the reason why they can't be added at start of suggestion), therefore it's also possible to type: /he and hit TAB.
See also: clearCmdLineSuggestions(), removeCmdLineSuggestion()
Mudlet VersionAvailable in Mudlet4.11+
Parameters
  • name: optional command line name, if skipped main command line will be used
  • suggestion - suggestion as a single word to add to tab completion (only the following are allowed: 0-9A-Za-z_)

Example:

addCmdLineSuggestion("help")

local suggestions = {"Pneumonoultramicroscopicsilicovolcanoconiosis", "supercalifragilisticexpialidocious", "serendipitous"}
for _, suggestion in ipairs(suggestions) do
  addCmdLineSuggestion(suggestion)
end

adjustStopWatch

adjustStopWatch(watchID/watchName, amount)
Adjusts the elapsed time on the stopwatch forward or backwards by the amount of time. It will work even on stopwatches that are not running, and thus can be used to preset a newly created stopwatch with a negative amount so that it runs down from a negative time towards zero at the preset time.
Parameters
  • watchID (number) / watchName (string): The stopwatch ID you get with createStopWatch() or the name given to that function or later set with setStopWatchName().
  • amount (decimal number): An amount in seconds to adjust the stopwatch by, positive amounts increase the recorded elapsed time.
Returns
  • true on success if the stopwatch was found and thus adjusted, or nil and an error message if not.
Example
-- demo of a persistent stopWatch used to real time a mission
-- called with a positive number of seconds it will start a "missionStopWatch"
-- unless there already is one in which case it will instead report on
-- the deadline. use 'stopStopWatch("missionStopWatch")' when the mission
-- is done and 'deleteStopWatch("missionStopWatch")' when the existing mission
-- is to be disposed of. Until then repeated use of 'mission(interval)' will
-- just give updates...
function mission(time)
  local missionTimeTable = missionTimeTable or {}

  if createStopWatch("missionStopWatch") then
    adjustStopWatch("missionStopWatch", -tonumber(time))
    setStopWatchPersistence("missionStopWatch", true)
    missionTimeTable = getStopWatchBrokenDownTime("missionStopWatch")

    echo(string.format("Get cracking, you have %02i:%02i:%02i hg:m:s left.\n", missionTimeTable.hours, missionTimeTable.minutes, missionTimeTable.seconds))
    startStopWatch("missionStopWatch")
  else
    -- it already exists, so instead report what is/was the time on it
    --[=[ We know that the stop watch exists - we just need to find the ID
      so we can get the running detail which is only available from the getStopWatches()
      table and that is indexed by ID]=]
    for k,v in pairs(getStopWatches()) do
      if v.name == "missionStopWatch" then
        missionTimeTable = v
      end
    end
    if missionTimeTable.isRunning then
      if missionTimeTable.elapsedTime.negative then
        echo(string.format("Better hurry up, the clock is ticking on an existing mission and you only have %02i:%02i:%02i h:m:s left.\n", missionTimeTable.elapsedTime.hours, missionTimeTable.elapsedTime.minutes, missionTimeTable.elapsedTime.seconds))
      else
        echo(string.format("Bad news, you are past the deadline on an existing mission by %02i:%02i:%02i h:m:s !\n", missionTimeTable.elapsedTime.hours, missionTimeTable.elapsedTime.minutes, missionTimeTable.elapsedTime.seconds))
      end
    else
      if missionTimeTable.elapsedTime.negative then
        echo(string.format("Well done! You have already completed a mission %02i:%02i:%02i h:m:s before the deadline ...\n", missionTimeTable.elapsedTime.hours, missionTimeTable.elapsedTime.minutes, missionTimeTable.elapsedTime.seconds))
      else
        echo(string.format("Uh oh! You failed to meet the deadline on an existing mission by %02i:%02i:%02i h:m:s !\n", missionTimeTable.elapsedTime.hours, missionTimeTable.elapsedTime.minutes, missionTimeTable.elapsedTime.seconds))
      end
    end
  end
end


-- in use:
lua mission(60*60)
Get cracking, you have 01:00:00 h:m:s left.

lua mission(60*60)
Better hurry up, the clock is ticking on an existing mission and you only have 00:59:52 h:m:s left.
Mudlet VersionAvailable in Mudlet4.4+

appendScript

appendScript(scriptName, luaCode, [occurrence])
Appends Lua code to the script "scriptName". If no occurrence given it sets the code of the first found script.
See also: permScript(), enableScript(), disableScript(), getScript(), setScript()
Returns
  • a unique id number for that script.
Parameters
  • scriptName: name of the script
  • luaCode: scripts luaCode to append
  • occurence: (optional) the occurrence of the script in case you have many with the same name
Example
-- an example of appending the script lua code to the first occurrence of "testscript"
appendScript("testscript", [[echo("This is a test\n")]], 1)
Mudlet VersionAvailable in Mudlet4.8+

appendCmdLine

appendCmdLine([name], text)
Appends text to the main input line.
See also: printCmdLine(), clearCmdLine()
Parameters
  • name: (optional) name of the command line. If not given, the text will be appended to the main commandline.
  • text: text to append


Example
-- adds the text "55 backpacks" to whatever is currently in the input line
appendCmdLine("55 backpacks")

-- makes a link, that when clicked, will add "55 backpacks" to the input line
echoLink("press me", "appendCmdLine'55 backpack'", "Press me!")

clearCmdLine

clearCmdLine([name])
Clears the input line of any text that's been entered.
See also: printCmdLine()
Parameters
  • name: (optional) name of the command line. If not given, the main commandline's text will be cleared.
Example
-- don't be evil with this!
clearCmdLine()

clearCmdLineSuggestions

clearCmdLineSuggestions([name])
Clears all suggestions for command line.
See also: addCmdLineSuggestion(), removeCmdLineSuggestion()
Parameter
  • name: (optional) name of the command line. If not given the main commandline's suggestions will be cleared.
clearCmdLineSuggestions()

createStopWatch

createStopWatch([name], [start immediately])
createStopWatch([start immediately])

Before Mudlet 4.4.0:

createStopWatch()
This function creates a stopwatch, a high resolution time measurement tool. Stopwatches can be started, stopped, reset, asked how much time has passed since the stop watch has been started and, following an update for Mudlet 4.4.0: be adjusted, given a name and be made persistent between sessions (so can time real-life things). Prior to 4.4.0 the function took no parameters and the stopwatch would start automatically when it was created.
Parameters
  • start immediately (bool) used to override the behaviour prior to Mudlet 4.4.0 so that if it is the only argument then a false value will cause the stopwatch to be created but be in a stopped state, however if a name parameter is provided then this behaviour is assumed and then a true value is required should it be desired for the stopwatch to be started on creation. This difference between the cases with and without a name argument is to allow for older scripts to continue to work with 4.4.0 or later versions of Mudlet without change, yet to allow for more functionality - such as presetting a time when the stopwatch is created but not to start it counting down until some time afterwards - to be performed as well with a named stopwatch.
  • name (string) a unique text to use to identify the stopwatch.
Returns
  • the ID (number) of a stopwatch; or, from 4.4.0: a nil + error message if the name has already been used.
See also: startStopWatch(), stopStopWatch(), resetStopWatch(), getStopWatchTime() or, from 4.4.0: adjustStopWatch(), deleteStopWatch(), getStopWatches(), getStopWatchBrokenDownTime(), setStopWatchName(), setStopWatchPersistence()
Example
(Prior to Mudlet 4.4.0) in a global script you can create all stop watches that you need in your system and store the respective stopWatch-IDs in global variables:
fightStopWatch = fightStopWatch or createStopWatch() -- create, or re-use a stopwatch, and store the watchID in a global variable to access it from anywhere

-- then you can start the stop watch in some trigger/alias/script with:
startStopWatch(fightStopWatch)

-- to stop the watch and measure its time in e.g. a trigger script you can write:
fightTime = stopStopWatch(fightStopWatch)
echo("The fight lasted for " .. fightTime .. " seconds.")
resetStopWatch(fightStopWatch)
(From Mudlet 4.4.0) in a global script you can create all stop watches that you need in your system with unique names:
createStopWatch("fightStopWatch") -- creates the stopwatch or returns nil+msg if it already exists

-- then you can start the stop watch (if it is not already started) in some trigger/alias/script with:
startStopWatch("fightStopWatch")

-- to stop the watch and measure its time in e.g. a trigger script you can write:
fightTime = stopStopWatch("fightStopWatch")
echo("The fight lasted for " .. fightTime .. " seconds.")
resetStopWatch("fightStopWatch")
You can also measure the elapsed time without having to stop the stop watch (equivalent to getting a lap-time) with getStopWatchTime().

Note Note: it's best to re-use stopwatch IDs if you can for Mudlet prior to 4.4.0 as they cannot be deleted, so creating more and more would use more memory. From 4.4.0 the revised internal design has been changed such that there are no internal timers created for each stopwatch - instead either a timestamp or a fixed elapsed time record is used depending on whether the stopwatches is running or stopped so that there are no "moving parts" in the later design and less resources are used - and they can be removed if no longer required.

deleteAllNamedTimers

deleteAllNamedTimers(userName)
Deletes all named timers and prevents them from firing any more. Information is deleted and cannot be retrieved.
See also
registerNamedTimer(), stopNamedTimer()
Mudlet VersionAvailable in Mudlet4.14+
Parameters
  • userName:
The user name the event handler was registered under.
Example
deleteAllNamedTimers("Demonnic") -- emergency stop or debugging situation, most likely.

deleteNamedTimer

success = deleteNamedTimer(userName, handlerName)
Deletes a named timer with name handlerName and prevents it from firing any more. Information is deleted and cannot be retrieved.
See also
registerNamedTimer(), stopNamedTimer()
Mudlet VersionAvailable in Mudlet4.14+
Parameters
  • userName:
The user name the event handler was registered under.
  • handlerName:
The name of the handler to stop. Same as used when you called registerNamedTimer()
Returns
  • true if successful, false if it didn't exist
Example
local deleted = deleteNamedTimer("Demonnic", "DemonVitals")
if deleted then
  cecho("DemonVitals deleted forever!!")
else
  cecho("DemonVitals doesn't exist and so could not be deleted.")
end

deleteStopWatch

deleteStopWatch(watchID/watchName)
This function removes an existing stopwatch, whether it only exists for this session or is set to be otherwise saved between sessions by using setStopWatchPersistence() with a true argument.
Parameters
Returns
  • true if the stopwatch was found and thus deleted, or nil and an error message if not - obviously using it twice with the same argument will fail the second time unless another one with the same name or ID was recreated before the second use. Note that an empty string as a name will find the lowest ID numbered unnamed stopwatch and that will then find the next lowest ID number of unnamed ones until there are none left, if used repetitively!
lua MyStopWatch = createStopWatch("stopwatch_mine")
true

lua display(MyStopWatch)
4

lua deleteStopWatch(MyStopWatch)
true

lua deleteStopWatch(MyStopWatch)
nil

"stopwatch with id 4 not found"

lua deleteStopWatch("stopwatch_mine")
nil

"stopwatch with name "stopwatch_mine" not found"
See also: createStopWatch(),
Mudlet VersionAvailable in Mudlet4.4+

Note Note: Stopwatches that are not set to be persistent will be deleted automatically at the end of a session (or if resetProfile() is called).

removeCmdLineSuggestion

removeCmdLineSuggestion([name], suggestion)
Remove a suggestion for tab completion for specified command line.
See also: addCmdLineSuggestion(), clearCmdLineSuggestions()
Mudlet VersionAvailable in Mudlet4.11+
Parameters
  • name: optional command line name, if skipped main command line will be used
  • suggestion - text to add to tab completion, non words characters at start and end of word should not be used (all characters except: `0-9A-Za-z_`)

Example:

removeCmdLineSuggestion("help")

disableAlias

disableAlias(name)
Disables/deactivates the alias by its name. If several aliases have this name, they'll all be disabled. If you disable an alias group, all the aliases inside the group will be disabled as well.
See also: enableAlias(), disableTrigger(), disableTimer(), disableKey(), disableScript().
Parameters
  • name:
The name of the alias. Passed as a string.
Examples
--Disables the alias called 'my alias'
disableAlias("my alias")

disableKey

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

disableScript

disableScript(name)
Disables a script that was previously enabled. Note that disabling a script only stops it from running in the future - it won't "undo" anything the script has made, such as labels on the screen.
See also: permScript(), appendScript(), enableScript(), getScript(), setScript()
Parameters
  • name: name of the script.
Example
--Disables the script called 'my script'
disableScript("my script")
Mudlet VersionAvailable in Mudlet4.8+

disableTimer

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

disableTrigger

disableTrigger(name)
Disables a permanent (one in the trigger editor) or a temporary trigger. When you disable a group, all triggers inside the group are disabled as well
See also: enableTrigger(), disableAlias(), disableTimer(), disableKey(), disableScript().
Parameters
  • name:
Expects the trigger ID that was returned by tempTrigger or other temp*Trigger variants, or the name of the trigger in case of a GUI trigger.
Example
-- Disables the trigger called 'my trigger'
disableTrigger("my trigger")

enableAlias

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

enableKey

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

Note Note:' From Version 3.10 returns true if one or more keys or groups of keys were found that matched the name given or false if not; prior to then it returns true if there were any keys - whether they matched the name or not!

enableScript

enableScript(name)
Enables / activates a script that was previously disabled.
See also: permScript(), appendScript(), disableScript(), getScript(), setScript()
Parameters
  • name: name of the script.
-- enable the script called 'my script' that you created in Mudlet's script section
enableScript("my script")
Mudlet VersionAvailable in Mudlet4.8+

enableTimer

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

-- it won't go off now
disableTimer(timerID)
-- it will continue going off again
enableTimer(timerID)

enableTrigger

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

-- it won't go off now when a line with matching text comes by
disableTrigger(triggerID)

-- and now it will continue going off again
enableTrigger(triggerID)

exists

exists(name/IDnumber, type)
Returns the number of things with the given name or number of the given type - and 0 if none are present. Beware that all numbers are true in Lua, including zero.
Parameters
  • name:
The name (as a string) or, from Mudlet 4.17.0, the ID number of a single item, (which will be that returned by a temp* or perm* function to create such an item to identify the item).
  • type:
The type can be 'alias', 'button' (Mudlet 4.10+), 'trigger', 'timer', 'keybind' (Mudlet 3.2+), or 'script' (Mudlet 3.17+).
See also: isActive(...)
Example
echo("I have " .. exists("my trigger", "trigger") .. " triggers called 'my trigger'!")
You can also use this alias to avoid creating duplicate things, for example:
-- this code doesn't check if an alias already exists and will keep creating new aliases
permAlias("Attack", "General", "^aa$", [[send ("kick rat")]])

-- while this code will make sure that such an alias doesn't exist first
-- we do == 0 instead of 'not exists' because 0 is considered true in Lua
if exists("Attack", "alias") == 0 then
    permAlias("Attack", "General", "^aa$", [[send ("kick rat")]])
end
Especially helpful when working with permTimer:
if not exists("My animation timer", "timer") then
  vdragtimer = permTimer("My animation timer", "", .016, onVDragTimer) -- 60fps timer!
end
 
enableTimer("My animation timer")

Note Note: A positive ID number will return either a 1 or 0 value and not a lua boolean true or false as might otherwise be expected, this is for constancy with the way the function behaves for a name.

getButtonState

getButtonState([ButtonNameOrID])
This function can be used within checkbox button scripts (2-state buttons) to determine the current state of the checkbox.
See also: setButtonState().

Note Note: Function can be used in any Mudlet script outside of a button's own script with parameter ButtonNameOrID available from Mudlet version 4.13.0+

Parameters
  • ButtonNameOrID:
a numerical ID or string name to identify the checkbox button.
Returns
  • 2 if the button has "checked" state, or 1 if the button is not checked. (or a nil and an error message if ButtonNameOrID did not identify a check-able button)
Example
-- check from within the script of a check-able button:
local checked = getButtonState()
if checked == 1 then
    hideExits()
else
    showExits()
end
-- check from anywhere in another Lua script of the same profile (available from Mudlet 4.13.0)
local checked, errMsg = getButtonState("Sleep")
if checked then
    shouldBeMounted = shouldBeMounted or false
    sendAll("wake", "stand")
    if shouldBeMounted then
        send("mount horse")
    end
else
    -- Global used to record if we were on a horse before our nap:
    shouldBeMounted = mounted or false
    if shouldBeMounted then
        send("dismount")
    end
    sendAll("sit", "sleep")
end

getCmdLine

getCmdLine([name])
Returns the current content of the given command line.
See also: printCmdLine()
Mudlet VersionAvailable in Mudlet3.1+
Parameters
  • name: (optional) name of the command line. If not given, it returns the text of the main commandline.
Example
-- replaces whatever is currently in the input line by "55 backpacks"
printCmdLine("55 backpacks")

--prints the text "55 backpacks" to the main console
echo(getCmdLine())

getConsoleBufferSize

local lineLimit, sizeOfBatchDeletion = getConsoleBufferSize([consoleName])
Returns, on success, the maximum number of lines a buffer (main window or a miniconsole) can hold and how many will be removed at a time when that limit is exceeded; returns a nil and an error message on failure.
See also: setConsoleBufferSize()
Parameters
  • consoleName:
(optional) The name of the window. If omitted, uses the main console.
Example
-- sets the main window's size and how many lines will be deleted
-- when it gets to that size to be as small as possible:
setConsoleBufferSize("main", 1, 1)
true

-- find out what the numbers are:
local lineLimit, sizeOfBatchDeletion = getConsoleBufferSize()
echo("\nWhen the main console gets to " .. lineLimit .. " lines long, the first " .. sizeOfBatchDeletion .. " lines will be removed.\n")
When the main console gets to 100 lines long, the first 1 lines will be removed.
Mudlet VersionAvailable in Mudlet4.17+

getNamedTimers

timers = getNamedTimers(userName)
Returns a list of all the named timers' names as a table.
See also
registerNamedTimer()
Mudlet VersionAvailable in Mudlet4.14+
Parameters
  • userName:
The user name the event handler was registered under.
Returns
  • a table of handler names. { "DemonVitals", "DemonInv" } for example. {} if none are registered
Example
  local timers = getNamedTimers("Demonnic")
  display(timers)
  -- {}
  registerNamedTimer("Test1", "testEvent", "testFunction")
  registerNamedTimer("Test2", "someOtherEvent", myHandlerFunction)
  timers = getNamedTimers("Demonnic")
  display(timers)
  -- { "Test1", "Test2" }

getProfileStats

getProfileStats()
Returns a table with profile statistics for how many triggers, patterns within them, aliases, keys, timers, and scripts the profile has. Similar to the Statistics button in the script editor, accessible to Lua scripting.
Mudlet VersionAvailable in Mudlet4.15+
Example
-- show all stats
display(getProfileStats())

-- check how many active triggers there are
activetriggers = getProfileStats().triggers.active
cecho(f"<PaleGreen>We have <SlateGrey>{activetriggers}<PaleGreen> active triggers!\n")

-- triggers can have many patterns, so let's check that as well
patterns = getProfileStats().triggers.patterns.active
triggers = getProfileStats().triggers.active
cecho(f"<PaleGreen>We have <SlateGrey>{patterns}<PaleGreen> active patterns within <SlateGrey>{triggers}<PaleGreen> triggers!\n")

getStopWatches

table = getStopWatches()
Returns a table of the details for each stopwatch in existence, the keys are the watch IDs but since there can be gaps in the ID number allocated for the stopwatches it will be necessary to use the pairs(...) rather than the ipairs(...) method to iterate through all of them in for loops!
Each stopwatch's details will list the following items: name (string), isRunning (boolean), isPersistent (boolean), elapsedTime (table). The last of these contains the same data as is returned by the results table from the getStopWatchBrokenDownTime() function - namely days (positive integer), hours (integer, 0 to 23), minutes (integer, 0 to 59), second (integer, 0 to 59), milliSeconds (integer, 0 to 999), negative (boolean) with an additional decimalSeconds (number of seconds, with a decimal portion for the milli-seconds and possibly a negative sign, representing the whole elapsed time recorded on the stopwatch) - as would also be returned by the getStopWatchTime() function.
Example
-- on the command line:
lua getStopWatches()
-- could return something like:
{
  {
    isPersistent = true,
    elapsedTime = {
      minutes = 15,
      seconds = 2,
      negative = false,
      milliSeconds = 66,
      hours = 0,
      days = 18,
      decimalSeconds = 1556102.066
    },
    name = "Playing time",
    isRunning = true
  },
  {
    isPersistent = true,
    elapsedTime = {
      minutes = 47,
      seconds = 1,
      negative = true,
      milliSeconds = 657,
      hours = 23,
      days = 2,
      decimalSeconds = -258421.657
    },
    name = "TMC Vote",
    isRunning = true
  },
  {
    isPersistent = false,
    elapsedTime = {
      minutes = 26,
      seconds = 36,
      negative = false,
      milliSeconds = 899,
      hours = 3,
      days = 0,
      decimalSeconds = 12396.899
    },
    name = "",
    isRunning = false
  },
  [5] = {
    isPersistent = false,
    elapsedTime = {
      minutes = 0,
      seconds = 38,
      negative = false,
      milliSeconds = 763,
      hours = 0,
      days = 0,
      decimalSeconds = 38.763
    },
    name = "",
    isRunning = true
  }
}
Mudlet VersionAvailable in Mudlet4.4+

getStopWatchTime

time = getStopWatchTime(watchID [or watchName from Mudlet 4.4.0])
Returns the time as a decimal number of seconds with up to three decimal places to give a milli-seconds (thousandths of a second) resolution.
Please note that, prior to 4.4.0 it was not possible to retrieve the elapsed time after the stopwatch had been stopped, retrieving the time was not possible as the returned value then was an indeterminate, meaningless time; from the 4.4.0 release, however, the elapsed value can be retrieved at any time, even if the stopwatch has not been started since creation or modified with the adjustStopWatch() function introduced in that release.
See also: createStopWatch(), startStopWatch(), stopStopWatch(), deleteStopWatch(), getStopWatches(), getStopWatchBrokenDownTime().
Returns a number
Parameters
  • watchID
The ID number of the watch.
Example
-- an example of showing the time left on the stopwatch
teststopwatch = teststopwatch or createStopWatch()
startStopWatch(teststopwatch)
echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))
tempTimer(1, [[echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))]])
tempTimer(2, [[echo("Time on stopwatch: "..getStopWatchTime(teststopwatch))]])
stopStopWatch(teststopwatch)

getStopWatchBrokenDownTime

brokenDownTimeTable = getStopWatchBrokenDownTime(watchID or watchName)
Returns the current stopwatch time, whether the stopwatch is running or is stopped, as a table, broken down into:
  • "days" (integer)
  • "hours" (integer, 0 to 23)
  • "minutes" (integer, 0 to 59)
  • "seconds" (integer, 0 to 59)
  • "milliSeconds" (integer, 0 to 999)
  • "negative" (boolean, true if value is less than zero)
See also: startStopWatch(), stopStopWatch(), deleteStopWatch(), getStopWatches(), getStopWatchTime().
Parameters
  • watchID / watchName
The ID number or the name of the watch.
Example
--an example, showing the presetting of a stopwatch.

--This will fail if the stopwatch with the given name
-- already exists, but then we can use the existing one:
local watchId = createStopWatch("TopMudSiteVoteStopWatch")
if watchId ~= nil then
  -- so we have just created the stopwatch, we want it
  -- to be saved for future sessions:
  setStopWatchPersistence("TopMudSiteVoteStopWatch", true)
  -- and set it to count down the 12 hours until we can
  -- revote:
  adjustStopWatch("TopMudSiteVoteStopWatch", -60*60*12)
  -- and start it running
  startStopWatch("TopMudSiteVoteStopWatch")

  openWebPage("http://www.topmudsites.com/vote-wotmud.html")
end

--[[ now I can check when it is time to vote again, even when
I stop the session and restart later by running the following
from a perm timer - perhaps on a 15 minute interval. Note that
when loaded in a new session the Id it gets is unlikely to be
the same as that when it was created - but that is not a
problem as the name is preserved and, if the timer is running
when the profile is saved at the end of the session then the
elapsed time will continue to increase to reflect the real-life
passage of time:]]

local voteTimeTable = getStopWatchBrokenDownTime("TopMudSiteVoteStopWatch")

if voteTimeTable["negative"] then
  if voteTimeTable["hours"] == 0 and voteTimeTable["minutes"] < 30 then
    echo("Voting for WotMUD on Top Mud Site in " .. voteTimeTable["minutes"] .. " minutes...")
  end
else
  echo("Oooh, it is " .. voteTimeTable["days"] .. " days, " .. voteTimeTable["hours"] .. " hours and " .. voteTimeTable["minutes"] .. " minutes past the time to Vote on Top Mud Site - doing it now!")
  openWebPage("http://www.topmudsites.com/vote-wotmud.html")
  resetStopWatch("TopMudSiteVoteStopWatch")
  adjustStopWatch("TopMudSiteVoteStopWatch", -60*60*12)
end
Mudlet VersionAvailable in Mudlet4.7+

getScript

getScript(scriptName, [occurrence])
Returns the script with the given name. If you have more than one script with the same name, specify the occurrence to pick a different one. Returns -1 if the script doesn't exist.
See also: permScript(), enableScript(), disableScript(), setScript(), appendScript()
Parameters
  • scriptName: name of the script.
  • occurrence: (optional) occurence of the script in case you have many with the same name.
Example
-- show the "New script" on screen
print(getScript("New script"))

-- an example of returning the script Lua code from the second occurrence of "testscript"
test_script_code = getScript("testscript", 2)
Mudlet VersionAvailable in Mudlet4.8+

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: what to say in the window title.
Examples
function whereisit()
  local path = invokeFileDialog(false, "Where should we save the file? Select a folder and click Open")

  if path == "" then return nil else return path end
end

isActive

isActive(name/IDnumber, type)
You can use this function to check if something, or somethings, are active.
Returns the number of active things - and 0 if none are active. Beware that all numbers are true in Lua, including zero.
Parameters
  • name:
The name (as a string) or, from Mudlet 4.17.0, the ID number of a single item, (which will be that returned by a temp* function to create such an item to identify the item).
  • type:
The type can be 'alias', 'button' (Mudlet 4.10+), 'trigger', 'timer', 'keybind' (Mudlet 3.2+), or 'script' (Mudlet 3.17+).
See also: exists(...)
Example
echo("I have " .. isActive("my trigger", "trigger") .. " currently active trigger(s) called 'my trigger'!")

-- Can also be used to check if a specific item is enabled or not.
if isActive("spellname", "trigger") > 0 then
  -- the spellname trigger is active
else
  -- it is not active
end

Note Note: A positive ID number that does not exist will still return a 0 value, this is for constancy with the way the function behaves for a name that does not refer to any item either. If necessary the existence of an item should be confirmed with exists(...) first.

isPrompt

isPrompt()
Returns true or false depending on if the line at the cursor position is a prompt. This infallible feature is available for games that supply GA events (to check if yours is one, look to bottom-right of the main window - if it doesn’t say <No GA>, then it supplies them).
Example use could be as a Lua function, making closing gates on a prompt real easy.
Example
-- make a trigger pattern with 'Lua function', and this will trigger on every prompt!
-- note that this is deprecated as we now have the prompt trigger type which does the same thing
-- the function can still be useful for detecting if you're running code on a prompt for other reasons
-- but you should be using a prompt trigger for this rather than a Lua function trigger.
return isPrompt()

killAlias

killAlias(aliasID)
Deletes a temporary alias with the given ID.
Parameters
  • aliasID:
The id returned by tempAlias to identify the alias.
-- deletes the alias with ID 5
killAlias(5)

killKey

killKey(name)
Deletes a keybinding with the given name. If several keybindings have this name, they'll all be deleted.
Parameters
  • name:
The name or the id returned by tempKey to identify the key.
Mudlet VersionAvailable in Mudlet3.2+
-- make a temp key
local keyid = tempKey(mudlet.key.F8, [[echo("hi!")]])

-- delete the said temp key
killKey(keyid)

killTimer

killTimer(id)
Deletes a tempTimer.

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

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

-- delete the timer
killTimer(timerID)
-- reset the reference to it
timerID = nil

killTrigger

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

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

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

Note Note: As of Mudlet version 4.16.0, triggers created with tempComplexRegexTrigger can only be killed using the name string specified during creation.

permAlias

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

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

permGroup

permGroup(name, itemtype, [parent])
Creates a new group of a given type. This group will persist through Mudlet restarts.
Parameters
  • name:
The name of the new group item you want to create.
  • itemtype :
The type of the item, can be one of the following:
trigger
alias
timer
script (available in Mudlet 4.7+)
key (available in Mudlet 4.11+)
  • parent (available in Mudlet 3.1+):
(optional) Name of existing item which the new item will be created as a child of. If none is given, item will be at the root level (not nested in any other groups)
Example
--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

permPromptTrigger

permPromptTrigger(name, parent, lua code)
Creates a persistent trigger for the in-game prompt that stays after Mudlet is restarted and shows up in the Script Editor.

Note Note: If the trigger is not working, check that the N: bottom-right has a number. This feature requires telnet Go-Ahead (GA) or End-of-Record (EOR) to be enabled in your game. Available in Mudlet 3.6+

Parameters
  • name is the name you’d like the trigger to have.
  • parent is the name of the group, or another trigger you want the trigger to go in - however if such a group/trigger doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
  • lua code is the script the trigger will do when it matches.
Example
permPromptTrigger("echo on prompt", "", [[echo("hey! this thing is working!\n")]])


permRegexTrigger

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

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

permBeginOfLineStringTrigger

permBeginOfLineStringTrigger(name, parent, pattern table, lua code)
Creates a persistent trigger that stays after Mudlet is restarted and shows up in the Script Editor. The trigger will go off whenever one of the regex patterns it's provided with matches. The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls.
Parameters
  • name is the name you’d like the trigger to have.
  • parent is the name of the group, or another trigger you want the trigger to go in - however if such a group/trigger doesn’t exist, it won’t do anything. Use "" to make it not go into any groups.
  • pattern table is a table of patterns that you’d like the trigger to use - it can be one or many.
  • lua code is the script the trigger will do when it matches.
Examples
-- Create a trigger that will match on anything that starts with "You sit" and do "stand".
-- It will not go into any groups, so it'll be on the top.
permBeginOfLineStringTrigger("Stand up", "", {"You sit"}, [[send ("stand")]])

-- Another example - lets put our trigger into a "General" folder and give it several patterns.
permBeginOfLineStringTrigger("Stand up", "General", {"You sit", "You fall", "You are knocked over by"}, [[send ("stand")]])

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

permSubstringTrigger

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

-- Or another trigger to highlight several different things
permSubstringTrigger("Highlight stuff", "General", {"pixie", "cat", "dog", "rabbit"},
[[selectString(line, 1) fg ("blue") bg("yellow") resetFormat()]])

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

permScript

permScript(name, parent, lua code)
Creates a new script in the Script Editor that stays after Mudlet is restarted.
Parameters
  • name: name of the script.
  • parent: name of the script group you want the script to go in.
  • lua code: is the code with string you are putting in your script.
Returns
  • a unique id number for that script.
See also: enableScript(), exists(), appendScript(), disableScript(), getScript(), setScript()
Example
-- create a script in the "first script group" group
permScript("my script", "first script group", [[send ("my script that's in my first script group fired!")]])
-- create a script that's not in any group; just at the top
permScript("my script", "", [[send ("my script that's in my first script group fired!")]])

-- enable Script - a script element is disabled at creation
enableScript("my script")

Note Note: The script is called once but NOT active after creation, it will need to be enabled by enableScript().

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

Note Note: If the lua code parameter is an empty string, then the function will create a script group instead.


Mudlet VersionAvailable in Mudlet4.8+

permTimer

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

-- enable timer - they start off disabled until you're ready
enableTimer("my timer")

Note Note: The timer is NOT active after creation, it will need to be enabled by a call to enableTimer() before it starts.

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

permKey

permKey(name, parent, [modifier], key code, lua code)
Creates a persistent key that stays after Mudlet is restarted and shows up in the Script Editor.
Parameters
  • name
name of the key.
  • parent
name of the timer group you want the timer to go in or "" for the top level.
  • modifier
(optional) modifier to use - can be one of mudlet.keymodifier.Control, mudlet.keymodifier.Alt, mudlet.keymodifier.Shift, mudlet.keymodifier.Meta, mudlet.keymodifier.Keypad, or mudlet.keymodifier.GroupSwitch or the default value of mudlet.keymodifier.None which is used if the argument is omitted. To use multiple modifiers, add them together: (mudlet.keymodifier.Shift + mudlet.keymodifier.Control)
  • key code
actual key to use - one of the values available in mudlet.key, e.g. mudlet.key.Escape, mudlet.key.Tab, mudlet.key.F1, mudlet.key.A, and so on. The list is a bit long to list out in full so it is available here.
set to -1 if you want to create a key folder instead.
  • lua code'
code you would like the key to run.
Returns
  • a unique id number for that key.
Mudlet VersionAvailable in Mudlet3.2+, creating key folders in Mudlet 4.10+
Example
-- create a key at the top level for F8
permKey("my key", "", mudlet.key.F8, [[echo("hey this thing actually works!\n")]])

-- or Ctrl+F8
permKey("my key", "", mudlet.keymodifier.Control, mudlet.key.F8, [[echo("hey this thing actually works!\n")]])

-- Ctrl+Shift+W
permKey("jump keybinding", "", mudlet.keymodifier.Control + mudlet.keymodifier.Shift, mudlet.key.W, [[send("jump")]])

Note Note: Mudlet by design allows duplicate names - so calling permKey with the same name will keep creating new keys. You can check if a key already exists with the exists() function. The key will be created even if the lua code does not compile correctly - but this will be apparent as it will be seen in the Editor.

printCmdLine

printCmdLine([name], text)
Replaces the current text in the input line, and sets it to the given text.
See also: clearCmdLine(), appendCmdLine()
Parameters
  • name: (optional) name of the command line. If not given, main commandline's text will be set.
  • text: text to set
printCmdLine("say I'd like to buy ")

raiseEvent

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

Note Note: possible arguments can be string, number, boolean, table, function, or nil.

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

Where the number of arguments that your event may receive is not fixed you can use ... as the last argument in the function declaration to handle any number of arguments. For example:

-- try this function out with "lua myscripthandler(1,2,3,4)"
function myscripthandler(a, b, ...)
  print("Arguments a and b are: ", a,b)
  -- save the rest of the arguments into a table
  local otherarguments = {...}
  print("Rest of the arguments are:")
  display(otherarguments)

  -- access specific otherarguments:
  print("First and second otherarguments are: ", otherarguments[1], otherarguments[2])
end

raiseGlobalEvent

raiseGlobalEvent(event_name, arg-1, … arg-n)
Like raiseEvent() this raises the event "event_name", but this event is sent to all other opened profiles instead. The profiles receive the event in circular alphabetical order (if profile "C" raised this event and we have profiles "A", "C", and "E", the order is "E" -> "A", but if "E" raised the event the order would be "A" -> "C"); execution control is handed to the receiving profiles so that means that long running events may lock up the profile that raised the event.
The sending profile's name is automatically appended as the last argument to the event.

Note Note: possible arguments can be string, number, boolean, or nil, but not table or function.

Example
-- from profile called "My game" this raises an event "my event" with additional arguments 1, 2, 3, "My game" to all profiles except the original one
raiseGlobalEvent("my event", 1, 2, 3)

-- want the current profile to receive it as well? Use raiseEvent
raiseEvent("my event", 1, 2, 3)
-- example of calling functions in one profile from another:
-- profile B:
control = control or {}
function control.updateStatus()
  disableTrigger("test triggers")
  print("disabling triggers worked!")
end

-- this handles calling the right function in the control table
function control.marshaller(_, callfunction)
  if control[callfunction] then control[callfunction]()
  else
    cecho("<red>Asked to call an unknown function: "..callfunction)
  end
end

registerAnonymousEventHandler("sysSendAllProfiles", "control.marshaller")

-- profile A:
raiseGlobalEvent("sysSendAllProfiles", "updateStatus")
raiseGlobalEvent("sysSendAllProfiles", "invalidfunction")
Mudlet VersionAvailable in Mudlet3.1.0+

Tip: you might want to add the profile name to your plain raiseEvent() arguments. This'll help you tell which profile your event came from similar to raiseGlobalEvent().

registerNamedTimer

success = registerNamedTimer(userName, timerName, time, functionReference, [repeating])
Registers a named timer with name timerName. Named timers are protected from duplication and can be stopped and resumed, unlike normal tempTimers. A separate list is kept for each userName, to enforce name spacing and avoid collisions
See also
tempTimer(), stopNamedTimer(), resumeNamedTimer(), deleteNamedTimer(), registerNamedEventHandler()
Mudlet VersionAvailable in Mudlet4.14+
Parameters
  • userName:
The user name the event handler was registered under.
  • timerName:
The name of the handler. Used to reference the handler in other functions and prevent duplicates. Recommended you use descriptive names, "hp" is likely to collide with something else, "DemonVitals" less so.
  • time:
The amount of time in seconds to wait before firing.
  • functionReference:
The function reference to run when the event comes in. Can be the name of a function, "handlerFunction", or the lua function itself.
  • repeating:
(optional) if true, the timer continue to fire until the stop it using stopNamedTimer()
Returns
  • true if successful, otherwise errors.
Example
-- establish a named timer called "Check balance" which runs balanceChecker() after 1 second
-- it is started automatically when registered, and fires only once despite being run twice
-- you wouldn't do this intentionally, but illustrates the duplicate protection
registerNamedTimer("Demonnic", "Check Balance", 1, balanceChecker)
registerNamedTimer("Demonnic", "Check Balance", 1, balanceChecker)

-- then the next time you want to make/use the same timer, you can shortcut it with
resumeNamedTimer("Demonnic", "Check Balance")

remainingTime

remainingTime(timer id number or name)
Returns the remaining time in floating point form in seconds (if it is active) for the timer (temporary or permanent) with the id number or the (first) one found with the name.
If the timer is inactive or has expired or is not found it will return a nil and an error message. It, theoretically could also return 0 if the timer is overdue, i.e. it has expired but the internal code has not yet been run but that has not been seen in during testing. Permanent offset timers will only show as active during the period when they are running after their parent has expired and started them.
Mudlet VersionAvailable in Mudlet3.20+
Example
tid = tempTimer(600, [[echo("\nYour ten minutes are up.\n")]])
echo("\nYou have " .. remainingTime(tid) .. " seconds left, use it wisely... \n")

-- Will produce something like:

You have 599.923 seconds left, use it wisely... 

-- Then ten minutes time later:

Your ten minutes are up.

resetProfileIcon

resetProfileIcon()
Resets the profile's icon in the connection screen to default.

See also: setProfileIcon().

Mudlet VersionAvailable in Mudlet4.0+
Example
resetProfileIcon()

resetStopWatch

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

resumeNamedTimer

success = resumeNamedTimer(userName, handlerName)
Resumes a named timer with name handlerName and causes it to fire again. One time unless it was registered as repeating.
See also
registerNamedTimer(), stopNamedTimer()
Mudlet VersionAvailable in Mudlet4.14+
Parameter
  • userName:
The user name the event handler was registered under.s
  • handlerName:
The name of the handler to resume. Same as used when you called registerNamedTimer()
Returns
  • true if successful, false if it didn't exist. If the timer is waiting to fire it will be restarted at 0.
Example
local resumed = resumeNamedTimer("Demonnic", "DemonVitals")
if resumed then
  cecho("DemonVitals resumed!")
else
  cecho("DemonVitals doesn't exist, so cannot resume it.")
end

setButtonState

setButtonState(ButtonNameOrID, checked)
Sets the state of a check-able ("push-down") type button from any Mudlet item's script - but does not cause the script or one of the commands associated with that button to be run/sent.
See also: getButtonState().
Mudlet VersionAvailable in Mudlet4.13+
Parameters
  • ButtonNameOrID:
The name of the button as a string or a unique ID (positive) integer number {for a name only one matching one will be affected - it will be the same one that the matching getButtonState() reports upon}.
  • checked:
boolean value that indicated whether the state required is down (true) or up (false).
Returns
  • A boolean value indicating true if the visible state was actually changed, i.e. had any effect. This function will return a nil and a suitable error message if the identifying name or ID was not found or was not a check-able (push-down) button item (i.e. was a non-checkable button or a menu or a toolbar instead).
Example
-- inside, for example, an initialization script for a GUI package:
setButtonState("Sleep", false)
setButtonState("Sit", false)
-- these are going to be used as "radio" buttons where setting one
-- of them will unset all the others, they will each need something
-- similar in their own scripts to unset all the others in the set
-- and also something to prevent them from being unset by clicking
-- on themselves:
setButtonState("Wimpy", true)
setButtonState("Defensive", false)
setButtonState("Normal", false)
setButtonState("Brave", false)
if character.type == "Warrior" then
    -- Only one type has this mode - and it can only be reset by
    -- something dying (though that could be us!)
    setButtonState("Beserk!!!", false)
end

setConsoleBufferSize

setConsoleBufferSize([consoleName], linesLimit, sizeOfBatchDeletion)
Sets the maximum number of lines a buffer (main window or a miniconsole) can hold. Default is 10,000.
Returns nothing on success (up to Mudlet 4.16) or true (from Mudlet 4.17); nil and an error message on failure.
Parameters
  • consoleName:
(optional) The name of the window. If omitted, uses the main console.
  • linesLimit:
Sets the amount of lines the buffer should have.

Note Note: Mudlet performs extremely efficiently with even huge numbers, but there is of course a limit to your computer's memory. As of Mudlet 4.7+, this amount will be capped to that limit on macOS and Linux (on Windows, it's capped lower as Mudlet on Windows is 32bit).

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

setProfileIcon

setProfileIcon(iconPath)
Set a custom icon for this profile in the connection screen.
Returns true if successful, or nil+error message if not.
See also: resetProfileIcon().
Mudlet VersionAvailable in Mudlet4.0+
Parameters
  • iconPath:
Full location of the icon - can be .png or .jpg with ideal dimensions of 120x30.
Example
-- set a custom icon that is located in an installed package called "mypackage"
setProfileIcon(getMudletHomeDir().."/mypackage/icon.png")

setScript

setScript(scriptName, luaCode, [occurrence])
Sets the script's Lua code, replacing existing code. If you have many scripts with the same name, use the 'occurrence' parameter to choose between them.
If you'd like to add code instead of replacing it, have a look at appendScript().
Returns -1 if the script isn't found - to create a script, use permScript().
See also: permScript(), enableScript(), disableScript(), getScript(), appendScript()
Returns
  • a unique id number for that script.
Parameters
  • scriptName: name of the script to change the code.
  • luaCode: new Lua code to set.
  • occurrence: The position of the script. Optional, defaults to 1 (first).
Example
-- make sure a script named "testscript" exists first, then do:
setScript("testscript", [[echo("This is a test\n")]], 1)
Mudlet VersionAvailable in Mudlet4.8+

setStopWatchName

setStopWatchName(watchID/currentStopWatchName, newStopWatchName)
Parameters
  • watchID (number) / currentStopWatchName (string): The stopwatch ID you get from createStopWatch() or the name supplied to that function at that time, or previously applied with this function.
  • newStopWatchName (string): The name to use for this stopwatch from now on.
Returns
  • true on success, nil and an error message if no matching stopwatch is found.

Note Note: Either currentStopWatchName or newStopWatchName may be empty strings: if the first of these is so then the lowest ID numbered stopwatch without a name is chosen; if the second is so then an existing name is removed from the chosen stopwatch.

setStopWatchPersistence

setStopWatchPersistence(watchID/watchName, state)
Parameters
  • watchID (number) / watchName (string): The stopwatch ID you get from createStopWatch() or the name supplied to that function or applied later with setStopWatchName()
  • state (boolean): if true the stopWatch will be saved.
Returns
  • true on success, nil and an error message if no matching stopwatch is found.
Sets or resets the flag so that the stopwatch is saved between sessions or after a resetProfile() call. If set then, if stopped the elapsed time recorded will be unchanged when the stopwatch is reloaded in the next session; if running the elapsed time will continue to increment and it will include the time that the profile was not loaded, therefore it can be used to measure events in real-time, outside of the profile!

Note Note: When a persistent stopwatch is reloaded in a later session (or after a use of resetProfile()) the stopwatch may not be allocated the same ID number as before - therefore it is advisable to assign any persistent stopwatches a name, either when it is created or before the session is ended.

setTriggerStayOpen

setTriggerStayOpen(name, number of lines)
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 of lines: 0 to close the chain, or a positive number to keep the chain open that much longer.
Examples
-- if you have a trigger that opens a chain (has some fire length) and you'd like it to be closed 
-- on the next prompt, you could make a prompt trigger inside the chain with a script of:
setTriggerStayOpen("Parent trigger name", 0)
-- to close it on the prompt!

startStopWatch

startStopWatch(watchName or watchID, [resetAndRestart])
Stopwatches can be stopped (with stopStopWatch()) and then re-started any number of times. To ensure backwards compatibility, if the stopwatch is identified by a numeric argument then, unless a second argument of false is supplied as well this function will also reset the stopwatch to zero and restart it - whether it is running or not; otherwise only a stopped watch can be started and only a started watch may be stopped. Trying to repeat either will produce a nil and an error message instead; also the recorded time is no longer reset so that they can now be used to record a total of isolated periods of time like a real stopwatch.
See also: createStopWatch(), stopStopWatch()
Parameters
  • watchID/watchName: The stopwatch ID you get with createStopWatch(), or from 4.4.0 the name assigned with that function or setStopWatchName().
  • resetAndRestart: Boolean flag needed (as false) to make the function from 4.4.0, when supplied with a numeric watch ID, to not reset the stopwatch and only start a previously stopped stopwatch. This behavior is automatic when a string watch name is used to identify the stopwatch but differs from how the function behaved prior to that version.
Returns
  • true on success, nil and an error message if no matching stopwatch is found or if it cannot be started (because the later style behavior was indicated and it was already running).
Examples
-- this is a common pattern for re-using stopwatches prior to 4.4.0 and starting them:
watch = watch or createStopWatch()
startStopWatch(watch)
After 4.4.0 the above code will work the same as it does not provide a second argument to the startStopWatch() function - if a false was used there it would be necessary to call stopStopWatch(...) and then resetStopWatch(...) before using startStopWatch(...) to re-use the stopwatch if the ID form is used, this is thus not quite the same behavior but it is more consistent with the model of how a real stopwatch would act.

stopAllNamedTimers

stopAllNamedTimers(userName)
Stops all named timers for userName and prevents them from firing any more. Information is retained and timers can be resumed.
See also
registerNamedTimer(), stopNamedTimer(), resumeNamedTimer()
Mudlet VersionAvailable in Mudlet4.14+
Example
stopAllNamedTimers("Demonnic") -- emergency stop situation, most likely.

stopNamedTimer

success = stopNamedTimer(userName, handlerName)
Stops a named timer with name handlerName and prevents it from firing any more. Information is stored so it can be resumed later if desired.
See also
registerNamedTimer(), resumeNamedTimer()
Mudlet VersionAvailable in Mudlet4.14+
Parameters
  • userName:
The user name the event handler was registered under.
  • handlerName:
The name of the handler to stop. Same as used when you called registerNamedTimer()
Returns
  • true if successful, false if it didn't exist or was already stopped
Example
local stopped = stopNamedTimer("Demonnic", "DemonVitals")
if stopped then
  cecho("DemonVitals stopped!")
else
  cecho("DemonVitals doesn't exist or already stopped; either way it won't fire any more.")
end

stopStopWatch

stopStopWatch(watchID or watchName)
"Stops" (though see the note below) the stop watch and returns (only the first time it is called after the stopwatch has been set running with startStopWatch()) the elapsed time as a number of seconds, with a decimal portion give a resolution in milliseconds (thousandths of a second). You can also retrieve the current time without stopping the stopwatch with getStopWatchTime(), getBrokenDownStopWatchTime().
See also: createStopWatch()
Parameters
Returns
  • the elapsed time as a floating-point number of seconds - it may be negative if the time was previously adjusted/preset to a negative amount (with adjustStopWatch()) and that period has not yet elapsed.
Examples
-- this is a common pattern for re-using stopwatches and starting them:
watch = watch or createStopWatch()
startStopWatch(watch)

-- do some long-running code here ...

print("The code took: "..stopStopWatch(watch).."s to run.")

tempAnsiColorTrigger

tempAnsiColorTrigger(foregroundColor[, backgroundColor], code[, expireAfter])
This is an alternative to tempColorTrigger() which supports the full set of 256 ANSI color codes directly and makes a color trigger that triggers on the specified foreground and background color. The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the expireAfter parameter.
Parameters
  • foregroundColor: The foreground color you'd like to trigger on.
  • backgroundColor: The background color you'd like to trigger on.
  • code to do: The code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function.
  • expireAfter: Delete trigger after a specified number of matches. You can make a trigger match not count towards expiration by returning true after it fires.

BackgroundColor and/or expireAfter may be omitted.

Color codes (note that the values greater than or equal to zero are the actual number codes that ANSI and the game server uses for the 8/16/256 color modes)
Special codes (may be extended in the future):
-2 = default text color (what is used after an ANSI SGR 0 m code that resets the foreground and background colors to those set in the preferences)
-1 = ignore (only one of the foreground or background codes can have this value - otherwise it would not be a color trigger!)
ANSI 8-color set:
0 = (dark) black
1 = (dark) red
2 = (dark) green
3 = (dark) yellow
4 = (dark) blue
5 = (dark) magenta
6 = (dark) cyan
7 = (dark) white {a.k.a. light gray}
Additional colors in 16-color set:
8 = light black {a.k.a. dark gray}
9 = light red
10 = light green
11 = light yellow
12 = light blue
13 = light magenta
14 = light cyan
15 = light white
6 x 6 x 6 RGB (216) colors, shown as a 3x2-digit hex code
16 = #000000
17 = #000033
18 = #000066
...
229 = #FFFF99
230 = #FFFFCC
231 = #FFFFFF
24 gray-scale, also show as a 3x2-digit hex code
232 = #000000
233 = #0A0A0A
234 = #151515
...
253 = #E9E9E9
254 = #F4F4F4
255 = #FFFFFF
Examples
-- This script will re-highlight all text in a light cyan foreground color on any background with a red foreground color
-- until another foreground 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.
tempAnsiColorTrigger(14, -1, [[selectString(matches[1],1) fg("red")]])
-- or:
tempAnsiColorTrigger(14, -1, function()
  selectString(matches[1], 1)
  fg("red")
end)

-- match the trigger only 4 times
tempColorTrigger(14, -1, [[selectString(matches[1],1) fg("red")]], 4)
Mudlet VersionAvailable in Mudlet3.17+

tempAlias

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

-- you can also delete the alias later with:
killAlias(myaliasID)

-- tempAlias also accepts functions (and thus closures) - which can be an easier way to embed variables and make the code for an alias look less messy:

local variable = matches[2]
tempAlias("^hi$", function () send("hello, " .. variable) end)

tempBeginOfLineTrigger

tempBeginOfLineTrigger(part of line, code, expireAfter)
Creates a trigger that will go off whenever the part of line it's provided with matches the line right from the start (doesn't matter what the line ends with). The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the expireAfter parameter. The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls.
Parameters
  • part of line: start of the line that you'd like to match. This can also be regex.
  • code to do: code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5.0).
  • expireAfter: Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
Examples
mytriggerID = tempBeginOfLineTrigger("Hello", [[echo("We matched!")]])

--[[ now this trigger will match on any of these lines:
Hello
Hello!
Hello, Bob!

but not on:
Oh, Hello
Oh, Hello!
]]

-- or as a function:
mytriggerID = tempBeginOfLineTrigger("Hello", function() echo("We matched!") end)
-- you can make the trigger match only a certain amount of times as well, 5 in this example:
tempBeginOfLineTrigger("This is the start of the line", function() echo("We matched!") end, 5)

-- if you want a trigger match not to count towards expiration, return true. In this example it'll match 5 times unless the line is "Start of line and this is the end."
tempBeginOfLineTrigger("Start of line", 
function()
  if line == "Start of line and this is the end." then
    return true
  else
    return false
  end
end, 5)

tempButton

tempButton(toolbar name, button text, orientation)
Creates a temporary button. Temporary means, it will disappear when Mudlet is closed.
Parameters
  • toolbar name: The name of the toolbar to place the button into.
  • button text: The text to display on the button.
  • orientation: a number 0 or 1 where 0 means horizontal orientation for the button and 1 means vertical orientation for the button. This becomes important when you want to have more than one button in the same toolbar.
Example
-- makes a temporary toolbar with two buttons at the top of the main Mudlet window 
lua tempButtonToolbar("topToolbar", 0, 0)
lua tempButton("topToolbar", "leftButton", 0)
lua tempButton("topToolbar", "rightButton", 0)

Note Note: This function is not that useful as there is no function yet to assign a Lua script or command to such a temporary button - though it may have some use to flag a status indication!

tempButtonToolbar

tempButtonToolbar(name, location, orientation)
Creates a temporary button toolbar. Temporary means, it will disappear when Mudlet is closed.
Parameters
  • name: The name of the toolbar.
  • location: a number from 0 to 3, where 0 means "at the top of the screen", 1 means "left side", 2 means "right side" and 3 means "in a window of its own" which can be dragged and attached to the main Mudlet window if needed.
  • orientation: a number 0 or 1, where 0 means horizontal orientation for the toolbar and 1 means vertical orientation for the toolbar. This becomes important when you want to have more than one toolbar in the same location of the window.
Example
-- makes a temporary toolbar with two buttons at the top of the main Mudlet window 
lua tempButtonToolbar("topToolbar", 0, 0)
lua tempButton("topToolbar", "leftButton", 0)
lua tempButton("topToolbar", "rightButton", 0)

tempColorTrigger

tempColorTrigger(foregroundColor, backgroundColor, code, expireAfter)
Makes a color trigger that triggers on the specified foreground and background color. Both colors need to be supplied in form of these simplified ANSI 16 color mode codes. The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the expireAfter parameter.

See also: tempAnsiColorTrigger

Parameters
  • foregroundColor: The foreground color you'd like to trigger on (for ANSI colors, see tempAnsiColorTrigger).
  • backgroundColor: The background color you'd like to trigger on (same as above).
  • code to do: The code to do when the trigger runs - wrap it in [[ and ]], or give it a Lua function, ie. function() <your code here> end (since Mudlet 3.5.0).
  • expireAfter: Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
Color codes
0 = default text color
1 = light black
2 = dark black
3 = light red
4 = dark red
5 = light green
6 = dark green
7 = light yellow
8 = dark yellow
9 = light blue
10 = dark blue
11 = light magenta
12 = dark magenta
13 = light cyan
14 = dark cyan
15 = light white
16 = dark white
Examples
-- This script will re-highlight all text in blue foreground colors on a black background with a red foreground color
-- on a blue background color until another color in the current line is being met. temporary color triggers do not 
-- offer match_all or filter options like the GUI color triggers because this is rarely necessary for scripting. 
-- A common usage for temporary color triggers is to schedule actions on the basis of forthcoming text colors in a particular context.
tempColorTrigger(9, 2, [[selectString(matches[1],1) fg("red") bg("blue")]])
-- or:
tempColorTrigger(9, 2, function()
  selectString(matches[1], 1)
  fg("red")
  bg("blue")
end)

-- match the trigger only 4 times
tempColorTrigger(9, 2, [[selectString(matches[1],1) fg("red") bg("blue")]], 4)

tempComplexRegexTrigger

tempComplexRegexTrigger(name, regex, code, multiline, fg color, bg color, filter, match all, highlight fg color, highlight bg color, play sound file, fire length, line delta, expireAfter)
Allows you to create a temporary trigger in Mudlet, using any of the UI-available options. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the expireAfter parameter.
Returns the trigger ID or nil and an error message (on error).
Parameters
  • name - The name you call this trigger. You can use this with killTrigger().
  • regex - The regular expression you want to match.
  • code - Code to do when the trigger runs. You need to wrap it in [[ ]], or give a Lua function (since Mudlet 3.5.0).
  • multiline - Set this to 1, if you use multiple regex (see note below), and you need the trigger to fire only if all regex have been matched within the specified line delta. Then all captures will be saved in multimatches instead of matches. If this option is set to 0, the trigger will fire when any regex has been matched.
  • fg color - The foreground color you'd like to trigger on - Not currently implemented.
  • bg color - The background color you'd like to trigger on - Not currently implemented.
  • filter - Do you want only the filtered content (=capture groups) to be passed on to child triggers? Otherwise also the initial line.
  • match all - Set to 1, if you want the trigger to match all possible occurrences of the regex in the line. When set to 0, the trigger will stop after the first successful match.
  • highlight fg color - The foreground color you'd like your match to be highlighted in. e.g. "yellow", "#ff0" or "#ffff00"
  • highlight bg color - The background color you'd like your match to be highlighted in. e.g. "red", "#f00" or "#ff0000"
  • play sound file - Set to the name of the sound file you want to play upon firing the trigger. e.g. "C:/windows/media/chord.wav"
  • fire length - Number of lines within which all condition must be true to fire the trigger.
  • line delta - Keep firing the script for x more lines, after the trigger or chain has matched.
  • expireAfter - Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.

Note Note: Set the options starting at multiline to 0, if you don't want to use those options. Otherwise enter 1 to activate or the value you want to use.

Note Note: If you want to use the color option, you need to provide both fg and bg together. - Not currently implemented.

Examples
-- This trigger will be activated on any new line received.
triggerNumber = tempComplexRegexTrigger("anyText", "^(.*)$", [[echo("Text received!")]], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, nil)

-- This trigger will match two different regex patterns:
tempComplexRegexTrigger("multiTrigger", "first regex pattern", [[]], 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, nil)
tempComplexRegexTrigger("multiTrigger", "second regex pattern", [[echo("Trigger matched!")]], 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, nil)

Note Note: For making a multiline trigger like in the second example, you need to use the same trigger name and options, providing the new pattern to add. Note that only the last script given will be set, any others ignored.

tempExactMatchTrigger

tempExactMatchTrigger(exact line, code, expireAfter)
Creates a trigger that will go off whenever the line from the game matches the provided line exactly (ends the same, starts the same, and looks the same). You don't need to use any of the regex symbols here (^ and $). The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the expireAfter parameter.
Parameters
  • exact line: exact line you'd like to match.
  • code: code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5.0).
  • expireAfter: Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
Examples
mytriggerID = tempExactMatchTrigger("You have recovered balance on all limbs.", [[echo("We matched!")]])

-- as a function:
mytriggerID = tempExactMatchTrigger("You have recovered balance on all limbs.", function() echo("We matched!") end)

-- expire after 4 matches:
tempExactMatchTrigger("You have recovered balance on all limbs.", function() echo("Got balance back!\n") end, 4)

-- you can also avoid expiration by returning true:
tempExactMatchTrigger("You have recovered balance on all limbs.", function() echo("Got balance back!\n") return true end, 4)

tempKey

tempKey([modifier], key code, lua code)
Creates a keybinding. This keybinding isn't temporary in the sense that it'll go off only once (it'll go off as often as you use it), but rather it won't be saved when Mudlet is closed.
See also: permKey(), killKey()
  • modifier
(optional) modifier to use - can be one of mudlet.keymodifier.Control, mudlet.keymodifier.Alt, mudlet.keymodifier.Shift, mudlet.keymodifier.Meta, mudlet.keymodifier.Keypad, or mudlet.keymodifier.GroupSwitch or the default value of mudlet.keymodifier.None which is used if the argument is omitted. To use multiple modifiers, add them together: (mudlet.keymodifier.Shift + mudlet.keymodifier.Control)
  • key code
actual key to use - one of the values available in mudlet.key, e.g. mudlet.key.Escape, mudlet.key.Tab, mudlet.key.F1, mudlet.key.A, and so on. The list is a bit long to list out in full so it is available here.
  • lua code'
code you'd like the key to run - wrap it in [[ ]].
Returns
  • a unique id number for that key.
Examples
keyID = tempKey(mudlet.key.F8, [[echo("hi")]])

anotherKeyID = tempKey(mudlet.keymodifier.Control, mudlet.key.F8, [[echo("hello")]])

-- bind Ctrl+Shift+W:
tempKey(mudlet.keymodifier.Control + mudlet.keymodifier.Shift, mudlet.key.W, [[send("jump")]])

-- delete it if you don't like it anymore
killKey(keyID)

-- tempKey also accepts functions (and thus closures) - which can be an easier way to embed variables and make the code for tempKeys look less messy:

tempKey(mudlet.key.F8, function() echo("Hi\n") end)

tempLineTrigger

tempLineTrigger(from, howMany, code)
Temporary trigger that will fire on n consecutive lines following the current line. This is useful to parse output that is known to arrive in a certain line margin or to delete unwanted output from the game - the trigger does not require any patterns to match on. The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the expireAfter parameter.
Parameters
  • from: from which line after this one should the trigger activate - 1 will activate right on the next line.
  • howMany: how many lines to run for after the trigger has activated.
  • code: code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5.0).
Example
-- Will fire 3 times with the next line from the game
tempLineTrigger(1, 3, function() print(" trigger matched!") end)

-- Will fire 5 lines after the current line and fire twice on 2 consecutive lines
tempLineTrigger(5, 2, function() print(" trigger matched!") end, 7)

tempPromptTrigger

tempPromptTrigger(code, expireAfter)
Temporary trigger that will match on the games prompt. The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the expireAfter parameter.

Note Note: If the trigger is not working, check that the N: bottom-right has a number. This feature requires telnet Go-Ahead to be enabled in the game.

Mudlet VersionAvailable in Mudlet3.6+
Parameters
  • code:
code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function.
  • expireAfter: (available in Mudlet 3.11+)
Delete trigger after a specified number of matches. You can make a trigger match not count towards expiration by returning true after it fires.
Example
tempPromptTrigger(function()
  echo("hello! this is a prompt!")
end)

-- match only 2 times:
tempPromptTrigger(function()
  echo("hello! this is a prompt!")
end, 2)

-- match only 2 times, unless the prompt is "55 health."
tempPromptTrigger(function()
  if line == "55 health." then return true end
end, 2)

tempRegexTrigger

tempRegexTrigger(regex, code, expireAfter)
Creates a temporary regex trigger that executes the code whenever it matches. The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the expireAfter parameter.
Parameters
  • regex: regular expression that lines will be matched on.
  • code: code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5.0).
  • expireAfter: Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.
Examples
-- create a non-duplicate trigger that matches on any line and calls a function
html5log = html5log or {}
if html5log.trig then killTrigger(html5log.trig) end
html5log.trig = tempRegexTrigger("^", [[html5log.recordline()]])
-- or a simpler variant:
html5log.trig = tempRegexTrigger("^", html5log.recordline)

-- only match 3 times:
tempRegexTrigger("^You prick (.+) twice in rapid succession with", function() echo("Hit "..matches[2].."!\n") end, 3)

-- since Mudlet 4.11+ you can use named capturing groups
tempRegexTrigger("^You see (?<material>\\w+) axe inside chest\\.", function() echo("\nAxe is " .. matches.material) end)

tempTimer

tempTimer(time, code to do[, repeating])
Creates a temporary one-shot timer and returns the timer ID, which you can use with enableTimer(), disableTimer() and killTimer() functions. You can use 2.3 seconds or 0.45 etc. After it has fired, the timer will be deactivated and destroyed, so it will only go off once. Here is a more detailed introduction to tempTimer.
Parameters
  • time: The time in seconds for which to set the timer for - you can use decimals here for precision. The timer will go off x given seconds after you make it.
  • code to do: The code to do when the timer is up - wrap it in [[ ]], or provide a Lua function.
  • repeating: (optional) if true, keep firing the timer over and over until you kill it (available in Mudlet 4.0+).
Examples
-- wait half a second and then run the command
tempTimer(0.5, function() send("kill monster") end)

-- echo between 1 and 5 seconds after creation
tempTimer(math.random(1, 5), function() echo("hi!") end) 

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

-- create a looping timer
timerid = tempTimer(1, function() display("hello!") end, true)

-- later when you'd like to stop it:
killTimer(timerid)

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

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

tempTimer( 3.8, [[echo("at the time of the tempTimer call I had ]] .. myGold .. [[ gold.")]] )

-- tempTimer also accepts functions (and thus closures) - which can be an easier way to embed variables and make the code for timers look less messy:

local variable = matches[2]
tempTimer(3, function () send("hello, " .. variable) end)

tempTrigger

tempTrigger(substring, code, expireAfter)
Creates a substring trigger that executes the code whenever it matches. The function returns the trigger ID for subsequent enableTrigger(), disableTrigger() and killTrigger() calls. The trigger is temporary in the sense that it won't stay when you close Mudlet, and it will go off multiple times until you disable or destroy it. You can also make it be temporary and self-delete after a number of matches with the expireAfter parameter.
Parameters
  • substring: The substring to look for - this means a part of the line. If your provided text matches anywhere within the line from the game, the trigger will go off.
  • code: The code to do when the trigger runs - wrap it in [[ ]], or give it a Lua function (since Mudlet 3.5)
  • expireAfter: Delete trigger after a specified number of matches (since Mudlet 3.11). You can make a trigger match not count towards expiration by returning true after it fires.

Example:

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

-- you can also write the same line as:
id = tempTrigger(target, function() selectString(target, 1) fg("gold") resetFormat() end)

-- or like so if you have a highlightTarget() function somewhere
id = tempTrigger(target, highlightTarget)
-- a simpler trigger to replace "hi" with "bye" whenever you see it
tempTrigger("hi", [[selectString("hi", 1) replace("bye")]])
-- this trigger will go off only 2 times
tempTrigger("hi", function() selectString("hi", 1) replace("bye") end, 2)
-- table to store our trigger IDs in
nameIDs = nameIDs or {}
-- delete any existing triggers we've already got
for _, id in ipairs(nameIDs) do killTrigger(id) end

-- create new ones, avoiding lots of ]] [[ to embed the name
for _, name in ipairs{"Alice", "Ashley", "Aaron"} do
  nameIDs[#nameIDs+1] = tempTrigger(name, function() print(" Found "..name.."!") end)
end
Additional Notes

tempTriggers begin matching on the same line they're created on.

If your code deletes and recreates the tempTrigger, or if you send a matching command again, it's possible to get into an infinite loop.

Make use of the expireAfter parameter, disableTrigger(), or killTrigger() to prevent a loop from forming.