Difference between revisions of "Manual:Miscellaneous Functions"

From Mudlet
Jump to navigation Jump to search
m (Typo)
(Added a comment regarding io.exists OS discrepancies.)
Line 196: Line 196:
 
===io.exists===
 
===io.exists===
 
; io.exists()
 
; io.exists()
: Checks to see if a given file or folder exists. If it exists, it’ll return the Lua true boolean value, otherwise false.
+
: Checks to see if a given file or folder exists.  
 +
: If it exists, it’ll return the Lua true boolean value, otherwise false.
 +
: Note: Behavior varies based on the user's operating system. Windows requires a specific file, while Linux will accept directories.
  
 
;Example
 
;Example
 
<lua>
 
<lua>
 +
-- This example works on Linux only
 
if io.exists("/home/vadi/Desktop") then
 
if io.exists("/home/vadi/Desktop") then
 
   echo("This folder exists!")
 
   echo("This folder exists!")
Line 206: Line 209:
 
end
 
end
  
 +
-- This example will work on both Windows and Linux.
 
if io.exists("/home/vadi/Desktop/file.tx") then
 
if io.exists("/home/vadi/Desktop/file.tx") then
 
   echo("This file exists!")
 
   echo("This file exists!")

Revision as of 21:03, 20 November 2012

Miscellaneous Functions

datetime:parse

datetime:parse(source, format, as_epoch)
Parses the specified source string, according to the format if given, to return a representation of the date/time. If as_epoch is provided and true, the return value will be a Unix epoch — the number of seconds since 1970. This is a useful format for exchanging date/times with other systems. If as_epoch is false, then a Lua time table will be returned. Details of the time tables are provided in the Lua Manual.
Supported Format Codes

<lua> %b = Abbreviated Month Name %B = Full Month Name %d = Day of Month %H = Hour (24-hour format) %I = Hour (12-hour format, requires %p as well) %p = AM or PM %m = 2-digit month (01-12) %M = 2-digit minutes (00-59) %S = 2-digit seconds (00-59) %y = 2-digit year (00-99), will automatically prepend 20 so 10 becomes 2010 and not 1910. %Y = 4-digit year. </lua>

disconnect

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

<lua> disconnect() </lua>

display

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

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

downloadFile

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

Note Note: Requires Mudlet 2.0+

Example

<lua> -- this example will check the Imperian homepage to see how many players are on right now

-- in an alias, download the Imperian homepage for stats processing downloadFile(getMudletHomeDir().."/page.html", "http://www.imperian.com/")

-- then create a new script with the name of downloaded_file, add the event handler -- for sysDownloadDone, and use this to parse the webpage and display the amount function downloaded_file(_, filename)

 -- is the file that downloaded ours?
 if not filename:match("page", 1, true) then return end
 -- parse our ownloaded file for the player count
 io.input(filename)
 local s = io.read("*all")
 local pc = s:match([[<a href='players.php%?search=who'>(%d+)</a>]])
 display("Imperian has "..tostring(pc).." players on right now.")
 io.open():close()
 os.remove(filename)

end </lua>

feedTriggers

feedTriggers( text )
This function will have Mudlet parse the given text as if it came from the MUD - one great application is trigger testing. You can use \n to represent a new line - you also want to use it before and after the text you’re testing, like so:

<lua> feedTriggers("\nYou sit yourself down.\n") </lua>

The function also accept ANSI color codes that are used in MUDs. A sample table can be found here.
Example

<lua> feedTriggers("\nThis is \27[1;32mgreen\27[0;37m, \27[1;31mred\27[0;37m, \27[46mcyan background\27[0;37m," .. "\27[32;47mwhite background and green foreground\27[0;37m.\n") </lua>

expandAlias

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

<lua> expandAlias("t rat")

-- don't echo the command expandAlias("t rat", false) </lua>

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

feedTriggers

feedTriggers( text )
This function will have Mudlet parse the given text as if it came from the MUD - one great application is trigger testing. You can use \n to represent a new line - you also want to use it before and after the text you’re testing, like so:

<lua> feedTriggers("\nYou sit yourself down.\n") </lua>

The function also accept ANSI color codes that are used in MUDs. A sample table can be found here.
Example

<lua> feedTriggers("\nThis is \27[1;32mgreen\27[0;37m, \27[1;31mred\27[0;37m, \27[46mcyan background\27[0;37m," .. "\27[32;47mwhite background and green foreground\27[0;37m.\n") </lua>

getMudletHomeDir

getMudletHomeDir()
Returns the current home directory of the current profile. This can be used to store data, save statistical information, or load resource files from packages.
Example

<lua> -- save a table table.save(getMudletHomeDir().."/myinfo.dat", myinfo)

-- or access package data. The forward slash works even on Windows fine local path = getMudletHomeDir().."/mypackagename" </lua>

getNetworkLatency

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

Need example

getTime

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

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

2012.02.18 00:52:52.489

Format expressions:

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

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

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

Example

<lua> -- Get time as a table @getTime()

-- Get time with default string @getTime(true)

-- Get time without date and milliseconds @getTime(true, "hh:mm:ss") </lua>

getTimestamp

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

Note Note: Available since 1.1.0-pre1

Example

<lua> --Echo the timestamp of the current line in a trigger: echo(getTimestamp(getLineCount())) </lua>

io.exists

io.exists()
Checks to see if a given file or folder exists.
If it exists, it’ll return the Lua true boolean value, otherwise false.
Note: Behavior varies based on the user's operating system. Windows requires a specific file, while Linux will accept directories.
Example

<lua> -- This example works on Linux only if io.exists("/home/vadi/Desktop") then

 echo("This folder exists!")

else

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

end

-- This example will work on both Windows and Linux. if io.exists("/home/vadi/Desktop/file.tx") then

 echo("This file exists!")

else

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

end </lua>

openUrl

openUrl (url)
Opens the default OS browser for the given URL.
Example

<lua> openUrl("http://google.com") openUrl("www.mudlet.org") </lua>

playSoundFile

playSoundFile(fileName)
This function plays a sound file. On 2.0, it can play most sound formats and up to 4 sounds simulaneously.
Parameters
  • fileName:
Exact path of the sound file.
Example

<lua> -- play a sound in Windows playSoundFile(C:\My folder\boing.wav)

-- play a sound in Linux playSoundFile(/home/myname/Desktop/boingboing.wav)

-- play a sound from a package playSoundFile(getMudletHomeDir().. /mypackage/boingboing.wav) </lua>

reconnect

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

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

registerAnonymousEventHandler

registerAnonymousEventHandler(event name, function name)
Registers a function to an event handler, not requiring you to set one up via s cript.
At the moment, it's not possible to use handlers inside namespaces, or unregister them.
Example

<lua> -- example taken from the God Wars 2 (http://godwars2.org) Mudlet UI - forces the window to keep to a certain size function keepStaticSize()

 setMainWindowSize(1280,720)

end -- keepStaticSize

registerAnonymousEventHandler("sysWindowResizeEvent", "keepStaticSize") </lua>

sendAll

sendAll(list of things to send, [echo back or not])
send()'s a list of things to the game. If you'd like the commands not to be shown, include false at the end.
Example

<lua> -- instead of using many send() calls, you can use one sendAll sendAll("outr paint", "outr canvas", "paint canvas") -- can also have the commands not be echoed sendAll("hi", "bye", false) </lua>

sendGMCP

sendGMCP(command)
Sends a GMCP message to the server. The IRE document on GMCP has information about what can be sent, and what tables it will use, etcetera.
See Also: GMCP Scripting
Example

<lua> --This would send "Core.KeepAlive" to the server, which resets the timeout sendGMCP("Core.KeepAlive")

--This would send a request for the server to send an update to the gmcp.Char.Skills.Groups table. sendGMCP("Char.Skills.Get {}")

--This would send a request for the server to send a list of the skills in the --vision group to the gmcp.Char.Skills.List table.

sendGMCP([[Char.Skills.Get { "group": "vision"}]])

--And finally, this would send a request for the server to send the info for --hide in the woodlore group to the gmcp.Char.Skills.Info table

sendGMCP([[Char.Skills.Get { "group": "woodlore", "name": "hide"}]]) </lua>

sendIrc

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

<lua> --This would send "hello from Mudlet!" to the channel #mudlet on freenode.net sendIrc("#mudlet", "hello from Mudlet!") --This would send "identify password" in a private message to Nickserv on freenode.net sendIrc("Nickserv", "identify password") </lua>

sendTelnetChannel102

sendTelnetChannel102(msg)
Sends a message via the 102 subchannel back to the MUD (that's used in Aardwolf). The msg is in a two byte format - see `help telopts` in Aardwolf on how that works.
Example

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

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

showColors

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

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

showColors(4)

spawn

spawn(read function, process to spawn)
Spawns a process and opens a communicatable link with it - read function is the function you'd like to use for reading output from the process, and t is a table containing functions specific to this connection - send(data), true/false = isRunning(), and close().
Example

<lua> -- simple example on a program that quits right away, but prints whatever it gets using the 'display' function local f = spawn(display, "ls") display(f.isRunning()) f.close() </lua>

wrapLine

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

<lua> --This will effectively have the same result as a call to deleteLine() but the buffer line will not be entirely removed. --Consequently, further calls to echo() etc. sort of functions are possible without using wrapLine() unnecessarily.

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