# general_doc

doc_name: triggers
title: Triggers
wiki_name: MushClientTriggers
description:
<b>What is a trigger exactly? </b>

Triggers match on something <b>received from</b> the MUD. They <b>trigger</b> some sort of action by MUSHclient, hence their name. 

They have a counterpart that matches on what <b>you type</b>, called an "alias". 


<hr/>

<b>What can I do with triggers?</b>

<ul>
  <li/>Colour a line to make it stand out (eg. colour chat channels in blue) 
  <li/>Colour individual words to make them stand out (eg. colour your character's name) 
  <li/>Highlight lines or words in bold, italic or underline 
  <li/>Gag annoying players by discarding lines which contain messages from them 
  <li/>Omit uninteresting things from the log file 
  <li/>Play a sound when certain things happen 
  <li/>Call a script routine to handle special events 
  <li/>Send a response back to the MUD (eg. "wield sword" when you are attacked) 
  <li/>Make editing attributes in a MUSH or MUCK easier 
</ul>

<hr/>

<b>How do I get a trigger to match?</b>

You normally match on incoming text, but you can also match on the colour of an incoming line. 

There are two sorts of matches you can do: 

<ul>
  <li/>Normal, with wildcards 
  <li/>Regular expression 
</ul>

<hr/>
<b>Normal matching</b>

A normal trigger (ie. with "regular expression" not checked) just matches on literally what is entered in the "Trigger" box, with optional wildcards represented by asterisks. You can have up to 999 asterisks, each representing some "unknown" text that might vary from line-to-line (eg. the name of someone or something). 

For example:

<ul>
  <li/>To match on pages: <code>Rhayctred pages: I saw Ibydan down by the river.</code>
  <li/>Trigger: <code>* pages: *</code>
</ul> 

<ul>
  <li/>To match on emotes: <code>From afar, Ocalef sighs</code>
  <li/>Trigger: <code>From afar, *</code>
</ul> 
  
One restriction on normal triggers is that you can't match on the "*" character itself, as it is a wildcard symbol. To do that, you would need to use a regular expression (see below), and "escape" the "*" by putting a backslash in front of it. 

For example, to match a line starting with an asterisk, you could match on this (with a regular expression): 

<code>
^\*
</code>

<hr/>
<b>Regular expression</b>

Regular expressions are a bit more complex, but give you more power over what you match on. 

A couple of simple rules: 

<ul>
<li/>^ - Matches the start of the line 
<li/>$ - Matches the end of the line 
<li/>. - Matches any character 
<li/>* - Matches zero or more of the previous character or set (so, ".*" matches any number of anything) 
<li/>+ - Matches one or more of the previous character or set (eg. "be+d" matches "bed", "beed", "beeed" and so on.) 
</ul>

<hr/>
<b>Making regular expressions check for alternatives</b>

Another powerful thing you can do with regular expressions is to look for "this" or "that". 

For instance, if you want to make a trigger warn you if one of Cigowyr, Herrach, Crael or Wiceadric has paged you, you can match like this: 

<code>
^(Cigowyr|Herrach|Crael|Wiceadric) pages\: .+$
</code>

The "|" symbol means "or", so the expression matches on one name or another. You can extend this idea to matching on whether they page or say something, like this: 

<code>
^(Cigowyr|Herrach|Crael|Wiceadric) (pages\:|says,) .+$
</code>

You probably want to check "ignore case" in case their name is given as "cigowyr" rather than "Cigowyr". 

<hr/>
<b>How to gag annoying players</b>

Simply set up a regular expression like the one above (substituting the relevant player names, of course), and then check "omit from output". Any paragraphs matching that trigger will be discarded from your output window. 

If you want to let them know you have them gagged you could put something like this in the "Send" box: 

<code>
page %1 = I am ignoring you.
</code>

Note - it might be unwise to set up an "auto-response" like the one above, because it could be used as the basis of a Denial Of Service (DOS) attack. If two players each set up an auto-response like that, then they will get into a loop, as the response from one player triggers the response from the other, and so on. Especially if they have "omit from output" set, they will not even be aware that they are causing a great overhead for the MUD, as it continually sends the messages backwards and forwards between the two players. 

What you could do to guard against this would be to make the trigger call a script routine, and in the script count how many times it has been called. After (say) 20 times it could notify you (using world.note) or disable the trigger, so you could take corrective action (like complaining to an admin about the other player). 

<hr/>
<b>Matching on everything except a word</b>

In some cases, you might want to match on everything except one word. For example, in SMAUG both room names and exits are displayed in white on black. You could detect room names by setting the match string like this: 

<code>
Trigger: ^(?!Exits:).*$
Match: white on black, bold
Regular expression: Checked
</code>

The expression "(?!Exits:)" means <b>not</b> the word "Exits:". 

Another real-life example was where a player wanted to congratulate other players when they reached another level, but not congratulate himself. He could do that like this: 

<code>
Trigger: ^(?!Caeth )(\w*) has risen to .*$
Regular expression: Checked
Send: say Congratulations %1!
</code>

This example assumes the player's name is Caeth.

<hr/>

<b>Trigger scripts</b>

Triggers can execute script commands by simply putting the command into the "send" box and selecting "send to script".

However for more complex scripts you can put scripts into your script file (see scripting configuration tab for the world) and then call the script from the trigger. To do this put the name of the script subroutine into the trigger's script box.

The script subroutine <b>must</b> have three arguments (four for Lua), as follows:

<ul>
<li/>Name of the trigger
<li/>The matching line
<li/>An array of the first 10 wildcards (Lua - all wildcards)
<li/>Lua only - a table of all the styles in the line
</ul>

An example script in the VBscript language would be:

<code>
sub MyTrigger (name, line, wildcards)
  world.Note "Trigger " &amp; name &amp; " matched."
  world.Note "Wildcard 1 was" &amp; wildcards (1)
end sub
</code>

Wildcard 10 is the entire matching sequence, which is not necessarily the same as the matching line in the case of regular expressions.

Other wildcards can be accessed by using the GetTriggerWildcard script routine (for example, named wildcards, or wildcards over number 9).

For Lua, wildcard 10 is the tenth wildcard, wildcard 11 is the eleventh wildcard and so on. All wildcards are returned in the Lua wildcards table. Wildcard subscript 0 is the entire matching line. Also in Lua named wildcards are returned in the wildcards table keyed by name.

For Lua, the fourth argument (which you can optionally supply) is returned with a table of each style run for the triggered line. Inside that table (which starts at 1 for the first style) is a table per style. Per style, you will get four entries:

<ul>
<li/>textcolour - the RGB colour of the text in that style run
<li/>backcolour - the RGB colour of the background colour in that style run
<li/>text - the text of that style run
<li/>length - the length of that style run
<li/>style - style flags (or'ed together): bold=1, underline=2, blink=4.
</ul>

<hr/>

<b>Wildcards</b>

A powerful feature in matching triggers or aliases is the ability to specify "wildcards" which are variable information that might change from time to time. 

For example:

<code>
* attacks you.
</code>

In this case the asterisk represents the name of the unknown attacker.

<b>Using the wildcard in the "send" box ...</b>

To use this unknown quantity you can refer to it as %1 (for the first wildcard) in the "send" box, like this:

<code>
kick %1
</code>

The second wildcard is %2, and so on. Wildcard %0 is a special case which represents the entire matching text.

For wildcards above 9 you can use this syntax:

<code>
kick %&lt;22&gt;
</code>

The number in the angled brackets can be from 0 to 999.

Also, if you use regular expressions, you can name wildcards, like this:

<code>
^(?P&lt;target&gt;.*) attacks you\.$
</code>

This names the wildcard as "target". You can then use this name in a similar way:

<code>
kick %&lt;target&gt;
</code>

<hr/>

<b>Trigger evaluation</b>

Normally when a trigger matches, no further matching is done, for the main world, or the current plugin. That way a match "deals with" the current situation (eg. if your character is hungry). However if you check "keep evaluating" then further triggers in the list are evaluated as well.

Regardless of the "keep evaluating" flag, triggers in other plugins are still processed, as each plugin is supposed to be independent.

However a script can call the StopEvaluatingTriggers if it needs to stop further evaluation, either in the current plugin, or all plugins. This lets a script decide, at run-time, whether or not it handled the situation.


doc_name: macros
title: Macro keys
wiki_name: MushClientMacros
description:
You can use the macros configuration to define "macros" - these are really user-defined keystrokes.

Macros are sent through the normal command interpreter, so they can consist of aliases, script commands, speedwalks and so forth.

As an extension, from version 3.53 onwards you can also define your own "accelerator" keys, which is another fancy word for "extended macros".

See the "Accelerator" function for more information. 

Unlike ordinary macros, which are fixed to certain predefined keystroke combinations, the Accelerator function lets you define any combination of keys (within reason), including redefining the behaviour of existing keystrokes (eg. Ctrl+N for New Document could become something else).

Any accelerators which have been defined with the Accelerator function will hide a corresponding macro from being shown in the GUI macro configuration screen, so as to avoid confusion about what the keystroke actually does.

<b>Hint</b>

To do more elaborate things (like expanding variables, running scripts) enter a nonsense word as what to send, and then make an alias to "catch" that word, and do the extra processing in the alias. One way of doing this is to use the Edit -> Generate Unique ID menu item to generate a unique word, like this:

381e051a828fb201b6914699

This is unlikely to be something you would normally want to type into the MUD. Then make an alias to match on "381e051a828fb201b6914699" (or whatever word you choose) and make the alias do things like expand variables, call scripts, etc.


doc_name: aliases
title: Aliases
wiki_name: MushClientAliases
description:
Aliases let you respond to something <b>you</b> have typed.

For example, an alias "GF" might expand to "open bag; get food"

You can also make aliases invoke scripts, make notes on the screen, do speedwalks, and many other things.

To respond to some text arriving from the MUD, use a trigger instead.

You can use wildcards to put "variable" information into the alias. For example, say you want to make an alias that gets something from your bag, and quaffs it, but the "something" might change from time to time, use an asterisk to represent the unknown thing. For example:

<code>Match: gq *</code>

Send:

<code>get %1 bag
quaff %1</code>

Then you might type:

<code>gq potion</code>

You can have up to 999 wildcards (which become %1 to %9) with %0 representing "the whole matching text". See below for how to access the higher numbered wildcards.

<hr/>

Another example, which uses two wildcards, might be used if you had to prepare a spell before using it.

<code>Match: c * *</code>

Send:

<code>prepare %1
cast %1 %2</code>

Then you might type:

<code>c heal gandalf</code>

<hr/>

<b>Alias scripts</b>

Aliases can execute script commands by simply putting the command into the "send" box and selecting "send to script".

However for more complex scripts you can put scripts into your script file (see scripting configuration tab for the world) and then call the script from the alias. To do this put the name of the script subroutine into the alias's script box.

The script subroutine <b>must</b>* have three arguments, as follows:

<ul>
<li/>Name of the alias
<li/>The matching line
<li/>An array of the first 10 wildcards
</ul>

* If you are using Lua, then the arguments are optional, as usual.

An example script in the VBscript language would be:

<code>
sub MyAlias (name, line, wildcards)
  Note "Alias " &amp; name &amp; " matched."
  Note "Wildcard 1 was" &amp; wildcards (1)
end sub
</code>

Wildcard 10 is the entire matching sequence, which is not necessarily the same as the matching line in the case of regular expressions.

Other wildcards can be accessed by using the GetAliasWildcard script routine (for example, named wildcards, or wildcards over number 9).

<hr/>

<b>Wildcards</b>

A powerful feature in matching triggers or aliases is the ability to specify "wildcards" which are variable information that might change from time to time. 

For example:

<code>
k *
</code>

In this case the asterisk represents the name of the unknown target you wish to kill.

<b>Using the wildcard in the "send" box ...</b>

To use this unknown quantity you can refer to it as %1 (for the first wildcard) in the "send" box, like this:

<code>
kick %1
</code>

The second wildcard is %2, and so on. Wildcard %0 is a special case which represents the entire matching text.

For wildcards above 9 you can use this syntax:

<code>
kick %&lt;22&gt;
</code>

The number in the angled brackets can be from 0 to 999.

Also, if you use regular expressions, you can name wildcards, like this:

<code>
^k (?P&lt;target&gt;.*)$
</code>

This names the wildcard as "target". You can then use this name in a similar way:

<code>
kick %&lt;target&gt;
</code>


doc_name: timers
title: Timers
wiki_name: MushClientTimers
description:
Timers let you set up periodic events (eg. every 10 seconds) or things that happen at a particular time (eg. 10:30 a.m.)

Timers can be once-off, which means they fire once and then delete themselves. This is useful if you only need to do the timed event once. (eg. cast a spell in 10 seconds).

Alternatively, timers can fire indefinitely, so you might, for example, eat food every 10 minutes.

Timers can send text to the MUD, make a note in the output window, invoke a script, do a speedwalk, or many other things.

You can have any number of timers, per world.

<b>Granularity of timers</b>

Note that the "granularity" of the timers is controlled by the "timers" tab in the "Preferences" menu item under the File menu.

What this means is that the interval set there (eg. 5 seconds) is the rate at which timers are tested to see if they have fired. If you want timers to be accurate to the nearest second, then the timer granularity must be set at 1 second. If having a timer fire to the nearest 5 seconds is satisfactory for you, then set the granularity to 5 seconds. Setting a smaller granularity improves the accuracy of timers, but may slow the program down slightly, particularly on slower PCs.

You can have timers tested every 10th of a second by setting the granularity to zero in the global preferences. This allows for finer resolution of timers than was previously possible.

<hr/>

<b>Timer scripts</b>

Timers can execute script commands by simply putting the command into the "send" box and selecting "send to script".

However for more complex scripts you can put scripts into your script file (see scripting configuration tab for the world) and then call the script from the timer. To do this put the name of the script subroutine into the alias's script box.

The script subroutine <b>must</b> have one argument which is the name of the timer.

An example script in the VBscript language would be:

<code>
sub MyTimer (name)
  world.Note "Timer " &amp; name &amp; " fired."
end sub
</code>


doc_name: keypad
title: Keypad navigation
wiki_name: KeypadNavigation
description:
If enabled, you can use the numeric keypad (usually on the right-hand side of the keyboard) to execute any commands you like.

The default is for direction commands, such as "8" for North, "2" for South, and so on, however you can configure the keys to be anything you like.

The text you specify is sent through the normal command processor, so the numeric keypad can be an alias, which might send a script, for example.

You can also specify actions if you hold down the Control key (eg. Ctrl+2).


doc_name: variables
title: Variables
wiki_name: MushClientVariables
description:
You can store any number of user-defined variables, which are "strings" - that is they can hold any text, including multiple lines. These are saved when you save the "world" file, so each world can remember things from one session to the next (eg. the names of potions you have found).

You can also store variables inside plugins. If the plugin is set to "save state" then any variables inside that plugin are automatically saved when the plugin closes.


doc_name: logging
title: Logging
wiki_name: MushClientLogging
description:
You can "log" sessions, which means to save them to disk in a text file.

You can use aliases and triggers to exclude certain things from the log file (such as spammy information that is not relevant to the log).

You can also log in HTML if you like, which preserves the colours of the original session.


doc_name: defaults
title: Default triggers/aliases/timers/macros/colours
wiki_name: MushClientDefaults
description:
The "defaults" concept is intended to allow you to have a single set of triggers/aliases/timers/macros/colours that are shared between many worlds. If you check "Override with default ..." in the appropriate part of the configuration interface, then existing items are discarded the next time the world is opened and replaced by the default ones, as described below.

This was added before plugins were added to MUSHclient, it is more flexible these days to put "shared" triggers etc. into a plugin and load that plugin into the worlds that need to share them.

To set up defaults to be shared across multiple worlds:

a) Open your favourite world, and then save as individual files your:

<ul>
<li/>Colours
<li/>Triggers
<li/>Aliases
<li/>Macros
<li/>Timers
</ul>

(there is a "save" button on each configuration screen to do this)

You do not need to do them all. For instance, if you only want to share colours, then only save the colours.

b) Use File -> Preferences -> Defaults to select the files you saved in the above step

c) Also select your preferred input and output font.

d) For all worlds that are to share these saved files, open that world, and then using the appropriate configuration screen (eg. colours, triggers) check the box "override with default".

From then on, the *next* time you open that world, it will load the world, and then load (and thus overwrite) the settings you have checked as "override with default".

Also, any new worlds will use the default settings, thus new worlds will quickly take on your default characteristics.

Note that the defaults, when loaded, *overwrite* your existing settings, so that the existing triggers, colours etc. are *lost*. If you really want to keep the existing settings, then you should save the world file under a different name (thus preserving the original).


doc_name: chat
title: Chat system
wiki_name: MushClientChat
description:
The chat features lets you do peer-to-peer chatting. That is, talk to other players without going through the MUD server. This could be useful for:

<ul>
<li/>privacy (your conversation cannot be listened to or logged by the MUD)

<li/>if the MUD is down you can still chat

<li/>talking when you normally can't (eg. in a silent room, if stunned, etc.)

<li/>automating interaction between people in a group (eg. PK groups)
</ul>

The chat features has detailed support in the MUSHclient scripting language.


doc_name: notepad
title: Notepad
wiki_name: MushClientNotepad
description:
MUSHclient has an internal notepad editor (similar to the Windows Notepad program).

This is useful for working on things whilst mudding. For example, you could type in a lengthy room description into a notepad window.

The notepad also lets you do useful conversions, like Unix to DOS, Base-64 encode/decode, quote forum codes, convert/unconvert HTML special characters.

You can also do find-and-replace.

There is a "bracket matcher" for finding the matching parenthesis in C code, or MUSHcode. This is configurable.


doc_name: mapper
title: Auto-mapper
wiki_name: AutoMapper
description:
<b>Introduction</b>

The intention of the mapper is that you can use it to generate a speed walk string (for use in an alias), by "teaching" it the way to go, rather than having to record each move you make on a bit of paper. For example, you might start at the city square, and walk around until you find a grocery shop, and then record the steps needed to find it, so you can find it again next time more easily. Also, by generating the reverse steps, you could move back from the grocery shop to the city square very easily.

This is not a GUI mapper (in other words, it doesn't attempt to draw maps on the screen), but is a system for recording the steps you have taken, with a view to re-using them later.

For a GUI mapper see this forum posting:

http://mushclient.com/forum/?id=10138


Once activated, it will do the following:

<b>Automatically record "standard" compass directions</b>

 These are defined as:

  n (north), s (south), e (east), w (west), ne, se, nw, sw, u (up) and d (down) 

  The directions in brackets are synonyms - either may be used.

<b>Record other commands</b>

On request, record any other commands which move you around, eg. "teleport", "go portal", "open door", "unlock gate". You can use Mapper special command to do this.

<b>Record comments</b>

To help work out where the mapping sequence is you can add comments manually (eg. "Outside Darkhaven"). Also, on an MXP-enabled MUD MUSHclient will automatically add room names to the auto-map sequence.

<b>Detect movement failure</b>

Automatically detect when a direction command fails to move you, and remove the failed direction from the mapping list. This is done by matching on a user-supplied "failure" string, eg. "Alas, you cannot go that way", "You cannot go north", "The gate is locked", "The door is closed". The failure string can be a "regular expression", thus combinations of the above may be expressed, eg. 

^(You cannot go that way|The gate is locked)$ 

<b>Remove backtracking</b>

Automatically (if desired) remove backtracking. For example, if you go North, and then South, you would normally end up back where you started. The auto-mapper will remove such instances, so that the end "direction string" does not contain false starts.

<b>Produce a speedwalk string</b>

Convert the recorded directions into a "speedwalk string".

<b>Produce a reverse speedwalk</b>

Also provide a "reverse speedwalk", so you can go back the way you came.

<b>Make a forwards and backwards alias</b>

On request, turn the direction string into an alias. Ditto for the reverse direction.

<b>Review your progress</b>

You can review the recorded steps at any point, and either keep adding to them, or start a new pathway.

<b>Correct mistakes</b>

If you accidentally record a direction that wasn't taken, it can be removed from the mapping sequence.

<b>Take the reverse route</b>

You can take the reverse route by clicking a single button.


doc_name: send_paste
title: Commented softcode
wiki_name: CommentedSoftcode
description:
This lets you send large amounts of data to the world in a single operation (eg. from a disk file). You might use this for sending attibutes to a MUSH or similar.

<b>Commented Softcode</b>

The purpose of this is to keep the (rather obscure) softcode commands in a text file with lots of comments in them. Then, in sending them to the MUSH the comments are stripped out.

Basically, there are two different kinds of softcode formatting - #-commented and @@-commented, with slightly different rules.  The basic part is you take a segment like

&amp;attrib Object=

Bleh

Bleh

Bleh

-

You start with the first line and append all subsequent lines until you get a '-' in the first column.  The different commenting styles are like this:

<b># This is #-commenting</b>

# Comments are determined by having a '#' in the first column.

&amp;attrib Object=

Bleh

Bleh  # This goes through as well - # not on first column

Bleh @@ In this case, @@ comments go through

-

<b>The other commenting style</b>

@@ This is @@-commenting

@@ Basically, anything after @@ on a line is stripped

<hr/>

MUSHclient determines which style to use by the first non-blank line of softcode. 

If the first line starts with "#" then hash-commenting is used, otherwise the "@@" commenting style is used.


doc_name: scripting
title: Scripting
wiki_name: MushClientScripting
description:
Scripting lets you extend the behaviour of MUSHclient to do almost anything you want.

You can script in one of (currently) eight script languages: VBscript, JScript, PerlScript, Tcl, Python, Lua, TCL and PHPscript. If you use plugins you can also have multiple script languages per session (a different one per plugin).

We recommend using <b>Lua</b> as the preferred scripting language nowadays. Lua ships with MUSHclient, so scripts written in Lua will be more easily exchanged with other MUSHclient users. Also Lua can be used if running under Wine on Linux PCs. The Lua script DLL is shipped with MUSHclient. With the exception of Lua, VBscript and JScript, you will need to download and install the other script engines before using scripts written in those languages.


<b>How do scripts get called?</b>

MUSHclient will call a function (or subroutine) in your script at various places you can specify. For instance, each trigger, timer or alias can call a script. Information about the trigger, alias and timer (such as its name, and the matching line) is passed to the script routine so it can react appropriately.

For example, you might make a trigger script that kept count of the number of times you levelled when playing a MUD.

You can also specify that scripts get called when other events happen, like "world open", "world connect", "new chat user" and so on.

<b>How do scripts communicate with MUSHclient?</b>

Scripts use the COM (Component Object Model) technology to send requests to MUSHclient or ask for information (except for Lua, see below). For example, you can use "Note" to tell MUSHclient to put a note in the output window, or "GetInfo" to find out information about the current world (like when it was connected).

Scripts use the "world" COM object to do this - this is available in all script languages. For example:

world.Note "Hello, there"

<b>Lua scripting</b>

Lua scripting does not use COM, and can thus be used in situations (like running under Wine on Linux) where COM is not working reliably.

Lua scripts are called directly from MUSHclient, generally with the same arguments as the COM scripts. There are some minor exceptions, these are noted under the relevant entries for each script function.


<b>Where do scripts go?</b>

You have a number of options for placing script routines -

1. In a script file which is used by the world (these can be shared between worlds). 

2. Each plugin you install can have scripts in it.

3. Triggers, aliases and timers can call a script functions directly from inside them, without needing a separate script file. This is called "send to script".

<b>Script functions</b>

There is extensive documentation about the script functions, including a list of all of them, at the web page:

http://www.gammon.com.au/mushclient/functions.htm

<b>Lua</b>

Commencing with version 3.52, the Lua language is supported. You can read more about Lua at:

http://www.lua.org/

Unlike the other languages, support for Lua is "hard-coded" into MUSHclient, it does not use the COM (Component Object Model) interface. This allows Lua to be supported in a consistent way, even on platforms that do not support other languages (eg. Linux).

<b>Forum posting about scripting</b>

There is a lengthy post on the MUSHclient forum about using scripting, see this:

http://www.gammon.com.au/forum/?id=6030


doc_name: speed_walking
title: Speed walking
wiki_name: SpeedWalking
description:
Speed walking is a way of quickly moving from one location to another. You can choose a "speed walk" prefix (for example, "#"). Once you have done that, and enabled speed walking in the "commands" configuration screen, then you can speed walk by entering the prefix followed by a string of direction letters, like this:

#4n3esuwdLW

This would move you: 4 times North, 3 times East, South, Up, West, Down and then "lock west"

<b>Actions</b>

Actions recognised are: C:close; O:open; L:lock; K:unlock (or nothing for no special action, just walk in that direction)

<b>Directions</b>

The directions recognised are: N:north, S:south, E:east, W:west, U:up, D:down (not case-sensitive).

<b>Filler</b>

You can also enter "F" for a speed walk "filler". This is for MUDs that reject multiple identical commands. For example, if you need to walk West 30 times, but your MUD disconnects you after 20 identical commands, enter:

#15w f 15w

The exact text that is sent by the "filler" is customisable from the "Input" world configuration screen. A suggested filler command would be something harmless, like LOOK.

<b>Multipliers</b>

You may also enter a one or two-digit multiplier in the range 1 to 99. The multiplier affects the *next* direction entered, e.g. "5s" means go South 5 times.

Spaces are accepted in the speed walk command, and ignored.

<b>Special commands</b>

If you need to enter other directions or commands (eg. NE for NorthEast) then you can put them in brackets. Otherwise, NE would be North, followed by East. Thus, to you North, West, and then NorthEast, you would enter:

N W (NE) 

To allow for reversing a speedwalk, you can also put the reverse direction after a slash. For example:

(NE/SW) (UP/DOWN) (OPEN/CLOSE) (LOCK/UNLOCK)

By doing this if you choose to reverse a speedwalk alias, all of the special commands will reverse correctly.

<b>Comments</b>

You can put comments into a speedwalk by putting it in braces, like this:

{ The Hall of the Mountain King }

This lets you describe what point you are up to in a lengthy speedwalk.

<b>Speed walk delay</b>

You can specify a time, between 0 and 30,000 milliseconds (that is, zero to 30 seconds) as a delay between each direction being sent to the MUD. This is for MUDs that don't allow very rapid walking. 1,000 milliseconds represent one second, so to have a 1.5 second delay, you would enter 1500 as the delay in milliseconds.

If you are using delayed speedwalking, any outstanding speedwalk (or other) commands are shown on the status line (up to a maximum of 50 characters). If there are more than 50 characters outstanding, you will see "..." following the speedwalk string.

If you change your mind about speedwalking (while some directions are still queued), you can use Discard queued commands to discard any queued commands.

<b>Bypassing the speedwalk queue</b>

You can set up an alias to "send to immediate" which will bypass the speedwalk queue. This lets you, for example, "say" to other players while you still have queued speedwalks.


doc_name: regexp
title: Regular Expressions
wiki_name: RegularExpressions
description:
<b>Perl-compatible Regular Expressions</b>

This is an excerpt from the file RegularExpressions.txt that is supplied as part of the MUSHclient distribution.

If you enable regular expressions for things such as triggers, aliases, "recall" window, "find" command, and so on, this is the syntax that is used.

Note that Lua regular expressions use a different syntax, see the help page for "Lua String functions".

<hr/>

The syntax and semantics of the regular expressions supported by PCRE are described below. Regular expressions are also described in the Perl documentation and in a number of other books, some of which have copious examples. Jeffrey Friedl's "Mastering Regular Expressions", published by O'Reilly (ISBN 1-56592-257), covers them in great detail. The description here is intended as reference documentation.

A regular expression is a pattern that is matched against a subject string from left to right. Most characters stand for themselves in a pattern, and match the corresponding characters in the subject. As a trivial example, the pattern

<code>
The quick brown fox
</code>

matches a portion of a subject string that is identical to itself. The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are encoded in the pattern by the use of meta-characters, which do not stand for themselves but instead are interpreted in some special way.

There are two different sets of meta-characters: those that are recognized anywhere in the pattern except within square brackets, and those that are recognized in square brackets. Outside square brackets, the meta-characters are as follows:

<code>
  \      general escape character with several uses
  ^      assert start of  subject  (or  line,  in  multiline mode)
  $      assert end of subject (or line, in multiline mode)
  .      match any character except newline (by default)
  [      start character class definition
  |      start of alternative branch
  (      start subpattern
  )      end subpattern
  ?      extends the meaning of (
        also 0 or 1 quantifier
        also quantifier minimizer
  *      0 or more quantifier
  +      1 or more quantifier
  {      start min/max quantifier
</code>

Part of a pattern that is in square brackets is called a "character class". In a character class the only meta-characters are: 

<code>
  \      general escape character
  ^      negate the class, but only if the first character
  -      indicates character range
  ]      terminates the character class
</code>

 The following sections describe the use of each of the meta-characters. 

<hr/>
<b>Backslash</b>

The backslash character has several uses. Firstly, if it is followed by a non-alphameric character, it takes away any special meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes.

For example, if you want to match a "*" character, you write "\*" in the pattern. This applies whether or not the following character would otherwise be interpreted as a meta- character, so it is always safe to precede a non-alphameric with "\" to specify that it stands for itself. In particular, if you want to match a backslash, you write "\\".

If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the pattern (other than in a character class) and characters between a "#" outside a character class and the next newline character are ignored. An escaping backslash can be used to include a whitespace or "#" character as part of the pattern.

A second use of backslash provides a way of encoding non- printing characters in patterns in a visible manner. There is no restriction on the appearance of non-printing characters, apart from the binary zero that terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to use one of the following escape sequences than the binary character it represents: 

<code>
  \a     alarm, that is, the BEL character (hex 07)
  \cx    "control-x", where x is any character
  \e     escape (hex 1B)
  \f     formfeed (hex 0C)
  \n     newline (hex 0A)
  \r     carriage return (hex 0D)
  \t     tab (hex 09)
  \xhh   character with hex code hh
  \ddd   character with octal code ddd, or backreference
</code>

The precise effect of "\cx" is as follows: if "x" is a lower case letter, it is converted to upper case. Then bit 6 of the character (hex 40) is inverted. Thus "\cz" becomes hex 1A, but "\c{" becomes hex 3B, while "\c;" becomes hex 7B.
 After "\x", up to two hexadecimal digits are read (letters can be in upper or lower case).

After "\0" up to two further octal digits are read. In both cases, if there are fewer than two digits, just those that are present are used. Thus the sequence "\0\x\07" specifies two binary zeros followed by a BEL character. Make sure you supply two digits after the initial zero if the character that follows is itself an octal digit.

The handling of a backslash followed by a digit other than 0 is complicated. Outside a character class, PCRE reads it and any following digits as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the expression, the entire sequence is taken as a back reference. A description of how this works is given later, following the discussion of parenthesized subpatterns.

Inside a character class, or if the decimal number is greater than 9 and there have not been that many capturing subpatterns, PCRE re-reads up to three octal digits following the backslash, and generates a single byte from the least significant 8 bits of the value. Any subsequent digits stand for themselves. For example:

<code>
  \040   is another way of writing a space
  \40    is the same, provided there are fewer than 40 previous capturing subpatterns
  \7     is always a back reference
  \11    might be a back reference, or another way of writing a tab
  \011   is always a tab
  \0113  is a tab followed by the character "3"
  \113   is the character with octal code 113 (since there can be no more than 99 back references)
  \377   is a byte consisting entirely of 1 bits
  \81    is either a back reference, or a binary zero followed by the two characters "8" and "1"
</code>

Note that octal values of 100 or greater must not be introduced by a leading zero, because no more than three octal digits are ever read.

All the sequences that define a single byte value can be used both inside and outside character classes. In addition, inside a character class, the sequence "\b" is interpreted as the backspace character (hex 08). Outside a character class it has a different meaning (see below).

The third use of backslash is for specifying generic character types:

<code>
  \d     any decimal digit
  \D     any character that is not a decimal digit
  \s     any whitespace character
  \S     any character that is not a whitespace character
  \w     any "word" character
  \W     any "non-word" character
</code>

Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any given character matches one, and only one, of each pair.

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale- specific matching is taking place (see "Locale support" above). For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.

These character type sequences can appear both inside and outside character classes. They each match one character of the appropriate type. If the current matching point is at the end of the subject string, all of them fail, since there is no character to match.

The fourth use of backslash is for certain simple assertions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below. The backslashed assertions are

<code>
  \b     word boundary
  \B     not a word boundary
  \A     start of subject (independent of multiline mode)
  \Z     end of subject or newline at  end  (independent  of multiline mode)
  \z     end of subject (independent of multiline mode)
</code>

These assertions may not appear in character classes (but note that "\b" has a different meaning, namely the backspace character, inside a character class).

A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively.

The \A, \Z, and \z assertions differ from the traditional circumflex and dollar (described below) in that they only ever match at the very start and end of the subject string, whatever options are set. They are not affected by the PCRE_NOTBOL or PCRE_NOTEOL options. If the startoffset argu- ment of pcre_exec() is non-zero, \A can never match. The difference between \Z and \z is that \Z matches before a newline that is the last character of the string as well as at the end of the string, whereas \z matches only at the end.

<hr/>
<b>Circumflex and dollar</b>

Outside a character class, in the default matching mode, the circumflex character is an assertion which is true only if the current matching point is at the start of the subject string. If the startoffset argument of pcre_exec() is non-zero, circumflex can never match. Inside a character class, circumflex has an entirely different meaning (see below).

Circumflex need not be the first character of the pattern if a number of alternatives are involved, but it should be the first thing in each alternative in which it appears if the pattern is ever to match that branch. If all possible alternatives start with a circumflex, that is, if the pattern is constrained to match only at the start of the subject, it is said to be an "anchored" pattern. (There are also other constructs that can cause a pattern to be anchored.)

A dollar character is an assertion which is true only if the current matching point is at the end of the subject string, or immediately before a newline character that is the last character in the string (by default). Dollar need not be the last character of the pattern if a number of alternatives are involved, but it should be the last item in any branch in which it appears. Dollar has no special meaning in a character class.

The meaning of dollar can be changed so that it matches only at the very end of the string, by setting the PCRE_DOLLAR_ENDONLY option at compile or matching time. This does not affect the \Z assertion.

The meanings of the circumflex and dollar characters are changed if the PCRE_MULTILINE option is set. When this is the case, they match immediately after and immediately before an internal "\n" character, respectively, in addition to matching at the start and end of the subject string. For example, the pattern /^abc$/ matches the subject string "def\nabc" in multiline mode, but not otherwise. Consequently, patterns that are anchored in single line mode because all branches start with "^" are not anchored in multiline mode, and a match for circumflex is possible when the startoffset argument of pcre_exec() is non-zero. The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set.

Note that the sequences \A, \Z, and \z can be used to match the start and end of the subject in both modes, and if all branches of a pattern start with \A is it always anchored, whether PCRE_MULTILINE is set or not.

<hr/>
<b>Full stop (period, dot)</b>

Outside a character class, a dot in the pattern matches any one character in the subject, including a non-printing character, but not (by default) newline. If the PCRE_DOTALL option is set, then dots match newlines as well. The handling of dot is entirely independent of the handling of circumflex and dollar, the only relationship being that they both involve newline characters. Dot has no special meaning in a character class.


<hr/>
<b>Square brackets</b>
    
An opening square bracket introduces a character class, terminated by a closing square bracket. A closing square bracket on its own is not special. If a closing square bracket is required as a member of the class, it should be the first data character in the class (after an initial circumflex, if present) or escaped with a backslash.

A character class matches a single character in the subject; the character must be in the set of characters defined by the class, unless the first character in the class is a circumflex, in which case the subject character must not be in the set defined by the class. If a circumflex is actually required as a member of the class, ensure it is not the first character, or escape it with a backslash.

For example, the character class [aeiou] matches any lower case vowel, while [^aeiou] matches any character that is not a lower case vowel. Note that a circumflex is just a convenient notation for specifying the characters which are in the class by enumerating those that are not. It is not an assertion: it still consumes a character from the subject string, and fails if the current pointer is at the end of the string.

When caseless matching is set, any letters in a class represent both their upper case and lower case versions, so for example, a caseless [aeiou] matches "A" as well as "a", and a caseless [^aeiou] does not match "A", whereas a caseful version would.

The newline character is never treated in any special way in character classes, whatever the setting of the PCRE_DOTALL or PCRE_MULTILINE options is. A class such as [^a] will always match a newline.

The minus (hyphen) character can be used to specify a range of characters in a character class. For example, [d-m] matches any letter between d and m, inclusive. If a minus character is required in a class, it must be escaped with a backslash or appear in a position where it cannot be interpreted as indicating a range, typically as the first or last character in the class.

It is not possible to have the literal character "]" as the end character of a range. A pattern such as [W-]46] is interpreted as a class of two characters ("W" and "-") followed by a literal string "46]", so it would match "W46]" or "-46]". However, if the "]" is escaped with a backslash it is interpreted as the end of range, so [W-\]46] is interpreted as a single class containing a range followed by two separate characters. The octal or hexadecimal representation of "]" can also be used to end a range.

Ranges operate in ASCII collating sequence. They can also be used for characters specified numerically, for example [\000-\037]. If a range that includes letters is used when caseless matching is set, it matches the letters in either case. For example, [W-c] is equivalent to [][\^_`wxyzabc], matched caselessly, and if character tables for the "fr" locale are in use, [\xc8-\xcb] matches accented E characters in both cases.

The character types \d, \D, \s, \S, \w, and \W may also appear in a character class, and add the characters that they match to the class. For example, [\dABCDEF] matches any hexadecimal digit. A circumflex can conveniently be used with the upper case character types to specify a more restricted set of characters than the matching lower case type. For example, the class [^\W_] matches any letter or digit, but not underscore.

All non-alphameric characters other than \, -, ^ (at the start) and the terminating ] are non-special in character classes, but it does no harm if they are escaped.


<hr/>
<b>Posix character classes</b>

Perl 5.6 (not yet released at the time of writing) is going to support the POSIX notation for character classes, which uses names enclosed by [: and :] within the enclosing square brackets. PCRE supports this notation. For example, 

<code>
       [01[:alpha:]%]
</code>

matches "0", "1", any alphabetic character, or "%". The supported class names are:

<code>
  alnum    letters and digits
  alpha    letters
  ascii    character codes 0 - 127
  cntrl    control characters
  digit    decimal digits (same as \d)
  graph    printing characters, excluding space
  lower    lower case letters
  print    printing characters, including space
  punct    printing characters, excluding letters and digits
  space    white space (same as \s)
  upper    upper case letters
  word     "word" characters (same as \w)
  xdigit   hexadecimal digits
</code>

The names "ascii" and "word" are Perl extensions. Another Perl extension is negation, which is indicated by a ^ character after the colon. For example,

<code>
  [12[:^digit:]]
</code>

matches "1", "2", or any non-digit. PCRE (and Perl) also recogize the POSIX syntax [.ch.] and [=ch=] where "ch" is a "collating element", but these are not supported, and an error is given if they are encountered. 

<hr/>
<b>Vertical bar</b>

Vertical bar characters are used to separate alternative patterns. For example, the pattern 

<code>
  gilbert|sullivan
</code>

matches either "gilbert" or "sullivan". Any number of alternatives may appear, and an empty alternative is permitted (matching the empty string). The matching process tries each alternative in turn, from left to right, and the first one that succeeds is used. If the alternatives are within a subpattern (defined below), "succeeds" means matching the rest of the main pattern as well as the alternative in the subpattern. 

<hr/>
<b>Subpatterns</b>

Subpatterns are delimited by parentheses (round brackets), which can be nested. Marking part of a pattern as a subpattern does two things: 

1. It localizes a set of alternatives. For example, the pattern 

<code>
  cat(aract|erpillar|)
</code>

matches one of the words "cat", "cataract", or "caterpillar". Without the parentheses, it would match "cataract", "erpillar" or the empty string.

2. It sets up the subpattern as a capturing subpattern (as defined above). When the whole pattern matches, that portion of the subject string that matched the subpattern is passed back to the caller via the ovector argument of pcre_exec(). Opening parentheses are counted from left to right (starting from 1) to obtain the numbers of the capturing subpatterns.

For example, if the string "the red king" is matched against the pattern

<code>
  the ((red|white) (king|queen))
</code>

the captured substrings are "red king", "red", and "king", and are numbered 1, 2, and 3.

The fact that plain parentheses fulfil two functions is not always helpful. There are often times when a grouping subpattern is required without a capturing requirement. If an opening parenthesis is followed by "?:", the subpattern does not do any capturing, and is not counted when computing the number of any subsequent capturing subpatterns. For example, if the string "the white queen" is matched against the pattern

<code>
  the ((?:red|white) (king|queen))
</code>

the captured substrings are "white queen" and "queen", and are numbered 1 and 2. The maximum number of captured substrings is 99, and the maximum number of all subpatterns, both capturing and non-capturing, is 200.

As a convenient shorthand, if any option settings are required at the start of a non-capturing subpattern, the option letters may appear between the "?" and the ":". Thus the two patterns

<code>
  (?i:saturday|sunday)
  (?:(?i)saturday|sunday)
</code>

match exactly the same set of strings. Because alternative branches are tried from left to right, and options are not reset until the end of the subpattern is reached, an option setting in one branch does affect subsequent branches, so the above patterns match "SUNDAY" as well as "Saturday".


<hr/>
<b>Repetition</b>

Repetition is specified by quantifiers, which can follow any of the following items: 

<code>
  a single character, possibly escaped
  the . metacharacter
  a character class
  a back reference (see next section)
  a parenthesized subpattern (unless it is  an  assertion - see below)
</code>

 The general repetition quantifier specifies a minimum and maximum number of permitted matches, by giving the two numbers in curly brackets (braces), separated by a comma. The numbers must be less than 65536, and the first must be less than or equal to the second. For example:

<code>
  z{2,4}
</code>

 matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special character. If the second number is omitted, but the comma is present, there is no upper limit; if the second number and the comma are both omitted, the quantifier specifies an exact number of required matches. Thus 

<code>
  [aeiou]{3,}
</code>

 matches at least 3 successive vowels, but may match many more, while 

<code>
  \d{8}
</code>

matches exactly 8 digits. An opening curly bracket that appears in a position where a quantifier is not allowed, or one that does not match the syntax of a quantifier, is taken as a literal character. For example, {,6} is not a quantifier, but a literal string of four characters.

The quantifier {0} is permitted, causing the expression to behave as if the previous item and the quantifier were not present.

For convenience (and historical compatibility) the three most common quantifiers have single-character abbreviations:

<code>
  *    is equivalent to {0,}
  +    is equivalent to {1,}
  ?    is equivalent to {0,1}
</code>

It is possible to construct infinite loops by following a subpattern that can match no characters with a quantifier that has no upper limit, for example: 

<code>
  (a?)*
</code>

Earlier versions of Perl and PCRE used to give an error at compile time for such patterns. However, because there are cases where this can be useful, such patterns are now accepted, but if any repetition of the subpattern does in fact match no characters, the loop is forcibly broken.

By default, the quantifiers are "greedy", that is, they match as much as possible (up to the maximum number of permitted times), without causing the rest of the pattern to fail. The classic example of where this gives problems is in trying to match comments in C programs. These appear between the sequences /* and */ and within the sequence, individual * and / characters may appear. An attempt to match C comments by applying the pattern

<code>
  /\*.*\*/
</code>

to the string

<code>
  /* first command */  not comment  /* second comment */
</code>

fails, because it matches the entire string due to the greediness of the .* item.

However, if a quantifier is followed by a question mark, then it ceases to be greedy, and instead matches the minimum number of times possible, so the pattern

<code>
  /\*.*?\*/
</code>

 does the right thing with the C comments. The meaning of the various quantifiers is not otherwise changed, just the preferred number of matches. Do not confuse this use of question mark with its use as a quantifier in its own right. Because it has two uses, it can sometimes appear doubled, as in

<code>
  \d??\d
</code>

which matches one digit by preference, but can match two if that is the only way the rest of the pattern matches.

If the PCRE_UNGREEDY option is set (an option which is not available in Perl) then the quantifiers are not greedy by default, but individual ones can be made greedy by following them with a question mark. In other words, it inverts the default behaviour.

When a parenthesized subpattern is quantified with a minimum repeat count that is greater than 1 or with a limited maximum, more store is required for the compiled pattern, in proportion to the size of the minimum or maximum.

If a pattern starts with .* or .{0,} and the PCRE_DOTALL option (equivalent to Perl's /s) is set, thus allowing the . to match newlines, then the pattern is implicitly anchored, because whatever follows will be tried against every character position in the subject string, so there is no point in retrying the overall match at any position after the first. PCRE treats such a pattern as though it were preceded by \A. In cases where it is known that the subject string contains no newlines, it is worth setting PCRE_DOTALL when the pattern begins with .* in order to obtain this optimization, or alternatively using ^ to indicate anchoring explicitly.

When a capturing subpattern is repeated, the value captured is the substring that matched the final iteration. For example, after

<code>
  (tweedle[dume]{3}\s*)+
</code>

has matched "tweedledum tweedledee" the value of the captured substring is "tweedledee". However, if there are nested capturing subpatterns, the corresponding captured values may have been set in previous iterations. For example, after

<code>
  /(a|(b))+/
</code>

 matches "aba" the value of the second captured substring is "b". 

<hr/>
<b>More ...</b>

There is more than this to regular expressions, however this is the basic part. See the documentation referred to at the start for more details.

<hr/>
<b>Author</b>

<code>
  Philip Hazel &lt;ph10@cam.ac.uk&gt;
  University Computing Service,
  New Museums Site,
  Cambridge CB2 3QG, England.

  Copyright (c) 1997-2000 University of Cambridge.
</code>


doc_name: contents
title: MUSHclient
wiki_name: MushClient
description:
Follow the links below for the main help topics ...

For online support, if your question is not answered here, please use the MUSHclient forum at our web site:

<code>
http://www.gammon.com.au/forum/
</code>


doc_name: mxp_callbacks
title: Scripting callbacks - MXP
wiki_name: MxpCallbacks
description:
When using MXP you can have various events call a script in your script file. This lets you customise your handling of things like errors, variables being set, and so on.

To add these script handlers, go to the Configuration screen -&gt; Scripts and click on the "MXP" button.

Then fill in the names of the routines you wish to call. The actual names do not matter, as long as they agree with the names used in your script file.

Some example scripts are shown below, these also illustrate the correct argument lists for each function.

<b>Plugins</b>

You can also call these routines inside plugins. In this case they must have fixed names, as there is no way of configuring the names to be used. Each item indicates the appropriate name to be used in a plugin.

<hr/>

<b>MXP startup</b>

This is called when MXP is started.

<b>Inside a plugin:</b> OnPluginMXPstart

<code>
function OnMXPStart ()
  Note "MXP started."
end -- function
</code>

<hr/>

<b>MXP shutdown</b>

This is called when MXP is stopped.

<b>Inside a plugin:</b> OnPluginMXPstop

<code>
function OnMXPShutdown ()
  Note "MXP stopped."
end -- function
</code>

<hr/>

<b>MXP errors</b>

This routine is called whenever an error, warning or information message is generated by MXP. This routine is called regardless of the "MXP debug" level you have set in your configuration screen. This lets you handle MXP errors in your own way. For instance, set the "MXP debug" level to "none" and display selected message to the output window or a notepad window.

<b>Note: Lua exception</b>

For Lua scripts, the arguments are passed in a different order than described below, namely:

<ul>
 <li/>Error number 
 <li/>Line number
 <li/>Error level
 <li/>Error message
</ul>

For example:

<code>
function OnMXPError (number, line, level, message)
  -- processing here 
end -- function
</code>

<hr/>

<b>Inside a plugin:</b> OnPluginMXPerror

The first argument is the "level" of the message, namely:

<ul>
  <li/>"E" - error
  <li/>"W" - warning
  <li/>"I" - information
  <li/>"A" - all other messages
</ul>

You might choose to only display "E" messages.

The second argument is the message number. This is a different number for each message, so you could choose to filter in (or out) particular message numbers. See the next posting for a list of message numbers.

The third argument is the line number of the current line in the output buffer (actually the count of lines in the output buffer). Effectively this identifies the line which caused the error, although in a sense the line is only a "nearby" line as MXP tags do not necessarily in themselves cause output to be sent to the output window.

Also, if the output buffer fills up, and lines at the top are discarded, then the line number will eventually become incorrect.

For example, if you have an error in line 1, the output buffer is 5,000 lines long, and you have received 10,000 lines, then clearly line 1 in the output buffer is not the same line 1 that reported the error. If you are trying to debug MXP problems you are advised to set your output buffer size to some large figure (eg. 100,000 lines) so that this problem does not arise quickly.

The fourth argument is the message text itself, which is usually pretty self-explanatory, and includes the name of the tag or item in error.

<code>
function OnMXPerror (level, number, line, message)
  if level == "E" and number ~= 1030 then 
    ColourNote ("white", "red", level .. "(" .. number .. "): " message)
  end if

-- do not display entities received (eg. &amp;lt; )
  if number == 20001 then 
     return 1
  end -- if

  return 0
end -- function
</code>

If you want to fine-tune which errors are shown in the standard MXP message window, you can return a non-zero value for any messages that are to be suppressed.

The example above returns 1 to suppress message 20001 from appearing in the message window. (This only applies in the main script file, not plugins).

<hr/>

<b>MXP start tag</b>

This routine is called when a "start" tag is parsed (successfully). For example, "&lt;send href='go west'&gt;".

<b>Inside a plugin:</b> OnPluginMXPopenTag

Some tags, marked as EMPTY, do not have end tags, and thus you would need to detect them here, rather than looking for their end tag.

The arguments are:

1. Tag name, eg. "send". The name will always be in lower case.
2. Arguments as provided, eg. "href='go west'"
3. Arguments parsed into a list. There will be one entry in the list for each argument. They will be supplied in the format "name=value", eg. "href=go west". If there were quotes around the argument value they will be removed. Thus, to find the name and the value, everything before the first "=" is the argument name, everything after the first "=" is the argument value. 

Arguments without a name will be named by an ascending number, eg. "1=prompt" means "prompt" is the first un-named argument.

<b>Note: Lua exception</b>

For Lua scripts, the arguments are passed as single string in the format:

<ul>
 <li/>tagname,arguments ... eg: sound,volume=1 pan=2 name="boing.wav"
</ul>

You are advised to not use world.Note to display the tag name/arguments to the output window, because this is likely to interfere with the MXP routines which are trying to work out, for example, which words to underline. You are best sending any debug information to another window, as in the example below.

<code>
function OnMXPStartTag (name, args, mylist)

  AppendToNotepad ("MXP", "Opening tag: " .. name .. "\n")
  AppendToNotepad ("MXP", "Argument list: "  .. args .. "\n")

  
  if mylist then
    for k, v in pairs (mylist) do
      AppendToNotepad ("MXP", "Arg " .. k .. " = " + v .. "\n")
    end -- for
  end -- if

  -- suppress color tags

  if name == "color" then 
    return 1
  end -- if

end -- function
</code>

If you want to suppress certain tags, you can return a non-zero value for the corresponding tag name, as in the example above.

<hr/>

<b>MXP end tag</b>

This routine is called when an "end" tag is parsed (successfully). For example, "&lt;/send&gt;".

<b>Inside a plugin:</b> OnPluginMXPcloseTag

Some tags, marked as EMPTY, do not have end tags.

The arguments are:

1. Tag name, eg. "send"
2. Value of "&amp;text;" variable. In other words, everything that appeared between the start tag and the end tag. This is limited to 1000 characters maximum.

<b>Note: Lua exception</b>

For Lua scripts, the arguments are passed as single string in the format:

<ul>
 <li/>tagname,text ... eg: send,eat newspaper
</ul>

For example, if you had:

&lt;send&gt;eat newspaper&lt;/send&gt;

The value of &amp;text; would be "eat newspaper".

<code>
function OnMXPEndTag (name, text)
  AppendToNotepad ("MXP", "Closing tag: " .. name .. "\n")
  AppendToNotepad ("MXP", "Text: " .. text .. "\n")
end -- function
</code>

<hr/>

<b>MXP set variable</b>

This is called when MXP sets a MUSHclient variable (by using the FLAG parameter on an element definition).

<b>Inside a plugin:</b> OnPluginMXPsetVariable

MXP variables are prefixed by "mxp_" so that they do not clash with variable names that you might already be using in your scripts.

The arguments are:

1. Variable name, eg. "mxp_hp"
2. Value of variable, eg. "22"

<b>Note: Lua exception</b>

For Lua scripts, the arguments are passed as single string in the format:

<ul>
 <li/>variable, value  ... eg: max_hp,22
</ul>

<code>
function OnMXPvariable (name, contents)
  Note ("Var " .. name .. " set to " .. contents)
end -- function
</code>

<b>Setting an MXP entity (plugins only)</b>

Inside a plugin you can detect an entity being changed by the MXP code from the MUD (not using the script SetEntity function).

<b>Inside a plugin:</b> OnPluginMXPsetEntity

The argument is: entityname=newvalue

<code>
function OnPluginMXPsetEntity (value)
  Note (value)  -- eg. foo=bar
end -- function
</code>


doc_name: data_types
title: Scripting data types
wiki_name: ScriptingDataTypes
description:
Below are the types of data you can supply to script routines (as shown in the "prototypes" for each script function).

<b>BOOL</b>

True or False.  

Lua type: boolean

<b>boolean</b>

True or False.

Lua type: boolean

<b>BSTR</b>

A character string (eg. "swordfish").

Lua type: string

Strings are stored as "null-terminated". That is, a byte with the value 0 (null) indicates the end of a string. Thus, strings may not contain imbedded null characters.

<b>IDispatch</b>

An object reference.

Lua type: not supported

<b>long</b>

A 32-bit number (from -2147483647 to +2147483647).

Lua type: number

<b>short</b>

A 16-bit number (from -32768 to +32767).

Lua type: number

<b>date</b>

A date/time field.

Lua type: number

<b>VARIANT</b>

A Visual-Basic "variant" data type, which can hold different types of data. A variant can be "null", "empty", or contain a number, character string, or an array, amongst other things. You can use the Visual Basic "VarType" function to find exactly what sort of data is in a variant. 

Lua type: any (all variables in Lua can be any type)

<b>void</b>

No return value.

Lua type: nil

<hr/>

The safest way to test for "true" or "false" is to assume that zero (0) is false, and any other value is true.

Similarly, to supply the value "true" simply supply a 1, and to supply the value "false", supply the value 0.


doc_name: function_list
title: Scripting functions list
wiki_name: MushClientFunctionList
description:
Below is a list of each script function in the current version of MUSHclient. Click on any link for more information about that function.


doc_name: errors
title: Scripting return codes
wiki_name: ScriptingReturnCodes
description:
Below is a list of the error codes that are returned by many script routines. Some scripts return different codes (such as variants), see those functions for more information.

The English meaning (eg. "The world is already open") can also be obtained by calling the ErrorDesc script function. The descriptions corresponding to an error code can also be found in Lua by indexing into the error_desc table (as in the "check" function below).

There is a function built into the Lua script space which will check for errors automatically:

<code>
function check (result)
  if result ~= error_code.eOK then
    error (error_desc [result] or 
           string.format ("Unknown error code: %i", result), 
           2) -- error level - whoever called this function
  end -- if
end -- function check 
</code>

If you pass an error code to the "check" function it will raise an error if the code is not valid (ie. not zero), with the appropriate error message. For example:

<code>
check (WindowShow ("foo", true))   -- raises error if window "foo" does not exist
</code>

The error codes can also be accessed from Lua using the error_code table (eg. error_code.eOK, error_code.eCannotPlaySound).
<hr/>


doc_name: starting
title: Getting started
wiki_name: GettingStarted
description:
If you just want to get started playing on a MUD, go to the Connection menu and choose "Quick Connect".

Then type in the MUD name, IP address, and port, click OK and you will be connected. Have fun!

<b>Help</b>

When any window or dialog is open, press F1 for help on that window.

To see what the various commands do (menus, and buttons on the button-bar below the menu) press Shift+F1. The cursor will change into a cursor with a question-mark next to it. Then select the menu or button you are interested in, and the appropriate help will be shown.


doc_name: activity
title: Activity window
wiki_name: ActivityWindow
description:
If you are playing in multiple worlds (MUDs) you can monitor their activity in a couple of ways.

<b>Activity Toolbar</b>

Click on the View menu -> Activity Toolbar to show the activity "buttons" if they are not already visible. You can drag them around, either docking them to the top, bottom or sides of the window, or leave them free as a floating window.

The buttons represent the first 10 worlds open, and change colour depending if the world is open, closed, or has new activity. You can click on any of the buttons to activate its related world window.

<b>Activity List</b>

This is a larger window that will show all open worlds (even if there are more than 10). It can be resized, moved, and the column order changed, to customise it to your requirements.


doc_name: info
title: Information
wiki_name: MushClientInformation
description:
There are various ways of getting information about the current world.

<ul>
<li/>The configuration "info" window shows details including line counts and memory used
<li/>You can find out what version of Windows Sockets is in use from the File Menu -> Windows Socket Information
<li/>You can find the text attributes of the current selection
<li/>Various script routines return information - see the list below.
</ul>


doc_name: infobar
title: Info bar - programmable information bar
wiki_name: MushClientInfoBar
description:
This is an additional "information bar" initially created above the normal MUSHclient status line. It uses the full screen width, and can be used to show information relevant to what you are doing (eg. current hit points).

The info bar has the following characteristics:

<ul>
<li/>Shared between all worlds 
<li/>Can only be updated from scripting
<li/>Can have multiple fonts, multiple colours, multiple font sizes and styles
<li/>Can be undocked and moved
<li/>Can be hidden or shown (from a script, or from the View menu)
</ul>

To access the info bar from scripting you can use the script routines described below.

Using world.Info to add text to the info bar does not replace existing content. The intention is that you initially use "InfoClear" to remove earlier content, then InfoFont and InfoColour to set up the info bar for the correct font and colour for the *next* piece of text. Then use world.Info to write text in the new font and colour.


doc_name: plugins
title: Plugins
wiki_name: MushClientPlugins
description:
Plugins are self-contained collections of related triggers, aliases, timers, variables and script routines. They are distributed as a single file, and installed by simply clicking on 'add' in the plugins dialog.

They are intended to allow the distribution of extensions to MUSHclient functionality in a simple way, without having to have complex instructions about amending script files, adding triggers and so on.

Plugins can also save their 'state' (ie. remember variables) so that variables that are set in one session will be remembered in another. This happens on a per-plugin, per-world basis.

You can quickly generate your own plugins by using the Plugin Wizard, which creates a plugin from your existing triggers, timers, aliases, variables and scripts.

Plugins can be given a sequence number (in the plugin file) which controls the order in which plugins are evaluated, and thus which plugin gets the first chance to evaluate triggers, aliases, etc.

The default sequence is 5000. Lower sequenced plugins get evaluated before higher sequenced ones.


doc_name: mxp
title: MXP - Mud Extension Protocol
wiki_name: MudExtensionProtocol
description:
<b>What is MXP?</b>

MXP stands for Mud Extension Protocol. 

It is a method for MUD servers to specify formatting and content information which goes beyond the scope of what is available with ANSI escape codes. For instance, using MXP a server can designate a line as a room description, exit, hyperlink, and so on. 

For example: 
 
<code>
This word is &lt;b&gt;bold&lt;/b&gt;.
&lt;RoomDesc&gt;This is a room description&lt;/RoomDesc&gt;
</code>

<b>MUSHclient support</b>

MUSHclient supports most of the MXP features as documented in the MXP specs. When receiving MXP commands from a MUD you will probably see hyperlinks (that you can click on) and pop-up menus (by right-mouse clicking on a link).

<b>Server support</b>

Various MUDs now support MXP. Probably one of the best is in the Dawn Of Time server, which has extensive support. Various other MUDs also have MXP support.


doc_name: colours
title: Colour management
wiki_name: MushClientColours
description:
<b>Colour Palette</b>

To understand how the program handles colours, it is necessary to discuss the concept of a colour "palette". MUSHclient recognises 8 ANSI "normal" colours (black, red, green, yellow, blue, magenta, cyan and white), and the same 8 colours in "bold". The codes to change colours may be sent by a particular MUD if the appropriate function calls are made by a room designer. The normal colour is white text on a black background.

However, the actual colours that are displayed depend on the colour palette for a particular world. For example "black" might actually display as grey, and "white" might actually display as green.

<b>Changing colours</b>

To change colours, use the "ANSI Colour" configuration dialog. You can right-mouse-click to copy colours from one colour swatch to another. Click on the colour swatches to change the colour.

<b>Custom colours</b>

Triggers and scripts can also use custom colours, which are a further 16 colours (pairs of foreground/background colours) which are configurable in the "Custom Colour" configuration dialog.

<b>RGB colours</b>

Triggers and scripts can also use the full RGB colour gamut - which is 256 (red) X 256 (green) X 256 (blue) colour combinations (a total of 16,777,216 possible colours). This allows for a wide range of colour presentation. In a trigger select the "other..." item from the colour combo-box. In scripts you can use things like world.ColourNote to send messages to the window in any colour.

<b>Saving colours</b>

Colours from one world can be saved to a "colour file" and then loaded into another world, thus keeping them all to the same colour scheme.

<b>Mapping colours</b>

From version 3.54 onwards you can also "map" one colour to another. This is provided to allow you to customise MXP colours which do not otherwise have a mechanism for being displayed differently. See the MapColour function for more details. This allows you to have a "last moment" mapping of a colour (that you don't like) to a different colour (that you prefer).


doc_name: utils
title: Utilities
wiki_name: MushClientUtilities
description:
There are various utility functions built into MUSHclient, some of which are in the built-in notepad.

Follow the links below for more details.


doc_name: register
title: Registration
wiki_name: MushClientRegistration
description:
MUSHclient is now distributed by the FreeWare method.


<b>AUTHOR</b>

MUSHclient has been written by Nick Gammon of Gammon Software Solutions.

Web page: http://www.gammon.com.au/

Contact/support: http://www.gammon.com.au/forum/


<b>COPYRIGHT</b>

MUSHclient is copyright 1995 - 2011 by Nick Gammon. All rights reserved worldwide.

MUSHclient is not in the public domain and Nick Gammon keeps its copyright.


<b>PERMISSION TO DISTRIBUTE</b>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.


<b>LIMITATION OF LIABILITY</b>

The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.


doc_name: group
title: Groups
wiki_name: MushClientGroups
description:
Triggers, aliases and timers can be placed into "groups".

This is simply a convenient way of managing a group of them for the purpose of:

<ul>
<li/>Enabling an entire group of triggers, aliases or timers
<li/>Disabling an entire group
<li/>Deleting an entire group
</ul>

You can make up any name you like for the group, it is just for your convenience.


doc_name: note
title: Notes
wiki_name: MushClientNotes
description:
There are various script functions for making notes to yourself in the output window.

You can also set triggers, aliases and timers to "send to output" which will send the "send text" to the output window (effectively doing a note).

Notes can be in the default "world note" colour, or you can use scripts to make notes in any colour.


doc_name: options
title: Option setting and retrieval
wiki_name: MushClientOptions
description:
Virtually every "world" option in MUSHclient can be set or queried using script routines, which lets you dynamically adjust the behaviour of the client as it is running.

See below for more information.


doc_name: send
title: Sending to the world
wiki_name: SendToWorld
description:
There are various ways of sending commands to the MUD. The main ways are:

<ul>
<li/>Sending in the usual way, which may append to any existing speedwalk queue
<li/>Queueing up a command to go at the speedwalk rate
<li/>Sending immediately, bypassing the speedwalk queue
</ul>


doc_name: world
title: World functions
wiki_name: MushClientWorldFunctions
description:
The "world" script functions let you obtain references to other open worlds which you can then use in your script to do things to them. For example, you could write your own "send to all worlds" script.


doc_name: features
title: Program features
wiki_name: MushClientFeatures
description:
Fast MUD/MUSH/MUCK/MOO client for Windows. Written in C++ for high speed and compact size. 

Has large scrollback buffer, command history, aliases, triggers, timers, keypad-navigation, speed-walking, and auto-say.

Supports scripting in Lua, VBscript, Jscript, PerlScript and Python, recognizes ANSI color codes, has user-defined macros, spell checking, proxy server support, chat system, built-in editor, and logging.

Also supports MUD extensions MCCP (Mud Client Compression Protocol) and MXP (Mud eXtension Protocol).

You can write your own plugins in any of the four supported scripting languages, or use ones written by others which are supplied with the program, or appear on our web site.

<b>Worlds</b>

<ul>
  <li/>Multiple worlds can be open at once
  <li/>You can automatically connect to a world (name and password)
  <li/>You can have multiple windows open per world
  <li/>Context-sensitive help is always available to explain how to use configuration screens, and other features.
  <li/>Details for an entire world, or just one of triggers/macros/aliases/colours/timers can be saved for re-use later.
  <li/>Supports MUD Client Compression Protocol (MCCP).
</ul>

<b>Output window</b>

<ul>
  <li/>Holds up to 500,000 previous lines in memory
  <li/>Fast scrolling back and forwards using keyboard or mouse
  <li/>Copy from output window for pasting into command window or elsewhere
  <li/>Can be frozen to review messages without them scrolling out of view
  <li/>Supports user-chosen font
  <li/>Supports user-chosen palette of colours
  <li/>Supports an additional 16 custom colours for triggers and other uses
  <li/>Recognises ANSI colours, hilight, inverse
  <li/>Automatic line wrapping at end of line so words are not chopped into two
  <li/>Selected messages from the MUD (eg. pages) can be displayed in a different colour to make them stand out (by using triggers)
</ul>
 
<b>Command (input) window</b>

<ul>
  <li/>Can be resized so lengthy commands can be entered
  <li/>Supports copy/cut/paste, arrow keys, home and end keys, and the mouse
  <li/>Last 5,000 commands entered are saved for recall and editing
  <li/>Previous commands can be viewed in a "command history" window for easy selection
  <li/>Commands can optionally be echoed in the output window
  <li/>Auto-completion allows partial words to be completed when you press &lt;tab&gt; based on a matching word in the output window.
  <li/>Spell-check automatically or on request
</ul>

<b>Logging</b>

<ul>
  <li/>Each world can log its output and (optionally) commands input
  <li/>Logging can commence automatically upon connection, appending to an existing log file if desired
  <li/>Logging can be filtered to remove pages, whispers etc.
  <li/>Filtering is controlled by using triggers
  <li/>Each log session can be prefixed and suffixed by identifying information (date, time etc.). The date/time can be automatically generated.
  <li/>Each log line can have a "line prefix" which may contain the date/time that line arrived
</ul>

<b>Notepad</b>

<ul>
  <li/>There is a custom "notepad" (text editor) for editing commands or any other purpose
  <li/>Notepad has spell-checker
  <li/>Notepad can do case conversions, and other conversions such as Unix to DOS
</ul>

<b>Macros (function keys)</b>

<ul>
  <li/>Up to 30 different keys can be used for single-keystroke entry of commands (F2 to F12, Ctrl+F2 to Ctrl+F12 and so on)
  <li/>Various other keystrokes are available for macros (Alt+A, Alt+B and others)
  <li/>You can use the numeric keypad also for single-keystroke movement
  <li/>Macro commands go through the command processor so they can call aliases, scripts, speedwalks etc.
</ul>

<b>Triggers</b>

<ul>
  <li/>Any number of "triggers" can be entered, per world. Triggers are used to match on output from the MUD, and then automatically perform a function (for example, page someone when they connect)
  <li/>Triggers can include wildcards (e.g. " * says * ") to match on variable text. The text matched on in the wildcard can be used in the response to the trigger.
  <li/>Alternatively, you can use "regular expressions" in triggers for precise matching
  <li/>Triggers can be set up to match the colour of incoming text
  <li/>Lines which activate a trigger can be displayed in a different colour, so you can use triggers to highlight certain types of game output.
  <li/>Individual words can be highlighted
  <li/>Lines which activate a trigger can also optionally play a sound file (a WAV file) so that you can use triggers to play sounds to alert you to certain events.
  <li/>Triggers can be used to omit certain types of displays from the log file (if one is open)
  <li/>Triggers can be used to copy the matched text back into the command (input) buffer for editing, if desired.
  <li/>Triggers can be used to send the matching text to the status line, or a notepad window, if desired.
  <li/>Triggers can call a script function.
</ul>

<b>Aliases</b>

<ul>
  <li/>Any number of "aliases" can be entered, per world. Aliases are a shorthand way of entering commands, for example: CLW could send "cure light wounds".
  <li/>Aliases can match the start of a command, anywhere in the command, or exactly the command by using wildcards. For example, if you set up an alias of "c" to mean "cure light wounds" and make it match exactly, then it will not clash with "close".
  <li/>Wildcards used in the alias can be used in the substitution text, so you can make aliases that can take "arguments"
  <li/>Aliases can expand out the contents of variables
  <li/>Aliases can match using regular expressions.
  <li/>Aliases can be used to omit the matching line from the log file, or the output window if desired
  <li/>Aliases can call a script function.
</ul>

<b>Timers</b>

<ul>
  <li/>Any number of "timers" can be entered, per world. Timers are used to cause things to happen at a particular time (eg. 9 pm) or an interval (eg. every 10 minutes).
  <li/>Timers can call a script function.
</ul>

<b>Speed walking</b>

<ul>
  <li/>You can optionally use speed walking to move quickly from one location to another. 
</ul>

<b>Command stacking</b>

<ul>
  <li/>You can optionally use command stacking to enter more than one command per line.
</ul>

<b>Status line</b>

<ul>
  <li/>Status line shows name of active MUD, when input was last received, number of lines received and other useful things. The status line can be updated by a trigger or a script routine.
</ul>

<b>Activity window</b>

<ul>
  <li/>You can open an "activity" window which is useful when connected to multiple MUDs. It shows if there is activity (output from) a MUD which is not the current (frontmost) window. A single keystroke then switches to that window.
</ul>

<b>Numeric keypad</b>

<ul>
  <li/>You can use the numeric keypad for movement in the MUD (press 8 to go north, 2 to go south, 4 to go west, 6 to go east, and so on). The actual commands that are sent for each keystroke are customisable.
  <li/>You can also use an "alternate set" of keystrokes on the numeric keypad by holding down the Control key. This lets you have a second set of actions (perhaps for during a fight).
</ul>

<b>Scripting</b>

<ul>
  <li/>You can write scripts in Lua, Vbscript, JavaScript, PerlScript or Python.
  <li/>The Lua script DLL is supplied with MUSHclient, and is thus always available with any additional installations being necessary.
  <li/>Various script extensions available to Lua scripts allow things like dialog boxes for asking questions, and list boxes or combo boxes for making choices.
</ul>

<b>Mapping</b>

<ul>
  <li/>You can automatically map the direction you are going as you walk around.
</ul>

<b>Plugins</b>

<ul>
  <li/>Related groups of triggers/aliases/timers/variables and scripts can be saved as a "plugin" - a separate file. 
  <li/>These can be easily generated using an inbuilt "plugin wizard". 
  <li/>Plugins can be shared between different worlds, saving the need to repeat triggers etc. in multiple worlds, and also makes it easier to fix problems in one central place.
  <li/>Plugins can be distributed to friends without them needing to understand scripting or load individual triggers into their worlds.
</ul>

<b>International</b>

<ul>
  <li/>Support for languages other than English, by the provision to read messages, menus and dialog boxes from external files.
</ul>


doc_name: plugin_callbacks
title: Scripting callbacks - plugins
wiki_name: MushClientPluginCallbacks
description:
The following subroutines/functions will be called in your plugin if they are present. The names are hard-coded, and a check is made to see if such names exist when the plugin is installed. As each one starts with the characters "OnPlugin" you should not get clashes with your own routines, provided you avoid using that particular prefix when naming your own functions. The example code below is in Lua.

<code>
<b>OnPluginInstall</b>
--
-- Plugin has been installed (added).
-- This is done immediately after the plugin has been added to the world's
-- list of plugins, and all plugin callback entry points found.
-- Note that any script instructions *outside* a plugin function will be
-- executed *before* this (as part of loading the script space).
--
function OnPluginInstall ()
end -- function


<b>OnPluginListChanged</b>
--
-- The list of plugins has changed
-- This includes: adding, removing, enabling, disabling a plugin
-- It also includes scripted loading and reloading of a plugin.
-- It is also called when loading a world file, after all plugins are loaded.
--
function OnPluginListChanged ()
end -- function


<b>OnPluginClose</b>
--
-- Plugin is being removed (closed).
-- Note that all plugins are closed when the world file is closed.
--
function OnPluginClose ()
end -- function

<b>OnPluginConnect</b>
--
-- This world has been connected (to the MUD).
-- This is done after the username and password have been sent (if any).
-- It is done after the NAWS telnet negotiation, if any. (IAC, WILL, TELOPT_NAWS)
-- It is done after the main world's "connect" function, if any.
-- It is done after the log file is opened, if one is being opened automatically.
--
function OnPluginConnect ()
end -- function

<b>OnPluginDisconnect</b>
--
-- This world has been disconnected (from the MUD).
-- This is called after the main world's "disconnect" function, if any.
-- It is called before the log file is closed, if any.
--
function OnPluginDisconnect ()
end -- function

<b>OnPluginSaveState</b>
--
-- The plugin is about to save its state
-- If you want to create new variables to be saved (eg. save script variables as MUSHclient variables)
--  now is the time to do it.
--
function OnPluginSaveState ()
end -- function

<b>OnPluginWorldSave</b>
--
-- The main world file is being saved.
-- If you want to save things (eg. to a database or separate file) when the
-- world file is being saved do it now).
--
function OnPluginWorldSave ()
end -- function

<b>OnPluginEnable</b>
--
-- The plugin is being enabled.
-- This is done *after* the enable flag is turned on.
--
function OnPluginEnable ()
end -- function

<b>OnPluginDisable</b>
--
-- The plugin is being disabled.
-- This is done *after* the enable flag is turned off.
--
function OnPluginDisable ()
end -- function

<b>OnPluginGetFocus</b>
--
-- The world to which the plugin belongs is getting the focus
--
function OnPluginGetFocus ()
end -- function

<b>OnPluginLoseFocus</b>
--
-- The world to which the plugin belongs is losing the focus
--
function OnPluginLoseFocus ()
end -- function


<b>OnPluginCommand</b>

--
--  The player has typed the command 'sText'
--  Return TRUE to process the command, FALSE to discard it
--
function OnPluginCommand (sText)
  return true -- process it
end -- function


<b>OnPluginCommandChanged</b>

--
--  The contents of the command window has changed.
--

function OnPluginCommandChanged ()
  -- check contents of command window (eg. spellcheck)
end -- function 


<b>OnPluginCommandEntered</b>

--
-- The player has typed the command 'sText' and pressed &lt;Enter&gt;
--
-- You can modify the command in this function, and return the modified string
--   which is what will be sent to the command processor.
-- If you return an empty string, that will sent to the command processor.
-- If you return a tab character on its own (\t or hex 09) then the command will be
-- discarded, and the command window cleared (unless auto-repeat commands is set).
--
-- If you return a carriage-return character on its own (\r or hex 0D) then the command will be
-- discarded, and retained in the command window.
--
-- This differs from OnPluginCommand which processes individual command lines,
--  after command stacking and other processing has taken place.
--
--  The example replaces line breaks by %r.
--
--  You might use this to implement your own "rules" for evaluating command stacking,
--  spell checking, keeping a command history, and so on.
--

function OnPluginCommandEntered (sText)
  return string.gsub (sText, "\n", "%r")
end -- function 

<b>OnPluginTabComplete</b>

--
-- The player has typed some text into the command window and pressed &lt;Tab&gt;.
--
-- The tab completion processing has found a match.
--
-- You can modify the match text in this function, and return the modified string
--   which is what will be replaced into the command window.

function OnPluginTabComplete (s)
  utils.msgbox (s)
end -- function 

<b>OnPluginSend</b>
--
--  MUSHclient is proposing to send 'sText' to the MUD
--  Return TRUE to send the text, FALSE to discard it
--
-- If any plugin returns FALSE, then the text is not actually sent.
--
-- If you want to know what was actually sent, use OnPluginSent (below).
--
--  If you call world.Send from within this function, OnPluginSend is not called again (however OnPluginSent will be).
--
function OnPluginSend (sText)
  return true  -- process it
end -- function

<b>OnPluginSent</b>
--
--  MUSHclient is definitely sending 'sText' to the MUD
--
-- This is called after every plugin has a chance to reject the text in the
--   OnPluginSend callback.
--
--  An example of use of this would be for an auto-mapper, as this function gets
--   text that has definitely been sent to the MUD.
--
-- If you call world.Send from within this callback, it will return an error.
--
--  OnPluginSent is supposed to be recording what is being sent, not sending new things.
--
function OnPluginSent (sText)
end -- function

<b>OnPluginLineReceived</b>
--
--  MUSHclient has received the line 'sText'
--  Return TRUE to process the text, FALSE to discard it
--
function OnPluginLineReceived (sText)
  return true  -- display it
end -- function

</code> 
In the case of routines like OnPluginCommand (about to send a command to the MUD), each plugin is scanned for every command entered. If any plugin returns FALSE, then that command is not processed. This gives each plugin a chance to respond to various commands, and suppress them if it wants to. Likewise for OnPluginSend (attempting to send a line of text to the MUD) and OnPluginLineReceived (received a line of text from the MUD).
<code>


<b>OnPluginPacketReceived</b>
--
--  MUSHclient has received the packet 'sText'
--
function OnPluginPacketReceived (sText)
end -- function
</code> 

This function is called when each incoming packet (data) arrives from the MUD. A packet does not necessarily start or end on line boundaries, and may consist of partial text lines, or more than one line. If compression (MCCP) is active, the packet is the data after decompression. 

Be warned that when compression is turned on, one packet may contain both uncompressed and compressed data (with the "turn on compression" sequence between them). Changing data in that packet may cause decompression to fail, if you alter the compressed part of the packet.

You can return data from this function (in version 3.59 onwards). If you do, then the returned data will replace the incoming data. In other words, you can change words, omit lines, add new lines, and MUSHclient will proceed as if the altered line had arrived from the MUD.

<code> 
<b>OnPluginPartialLine</b>
</code>
This will be called when one of these events occurs:

<ul>
<li/> A line fills up (eg. you hit 80 characters if that is your screen width)
<li/> A newline is received
<li/> A partial packet is received, and no more input is currently available
</ul>

The plugin is passed the current line - not just the new text - (which may or may not be "full" if the third condition is met) - which it can then test or pass into a regular expression for more complex testing.

This is intended to catch those situations where you need an immediate update (eg. a prompt line, entering a username/password when the newline is not present) on data received from the MUD.

Note that triggers will <b>still</b> be evaluated in the usual way, at the usual time. The plugin callback just gives you the chance to get at it sooner.
<code>

function OnPluginPartialLine (sText)
  AppendToNotepad ("test", sText . "\r\n")
end -- function

</code>

<code> 
<b>OnPluginBroadcast</b>
</code>

When a script calls BroadcastPlugin then all installed plugins are checked for a function OnPluginBroadcast. If present, it is called with 4 arguments:

<ul>
<li/>The message number (the first argument to BroadcastPlugin).
<li/>The ID of the calling plugin, or an empty string if BroadcastPlugin was called from the main script file.
<li/>The name of the calling plugin, or an empty string if BroadcastPlugin was called from the main script file.
<li/>The Text argument (the second argument to BroadcastPlugin)
</ul>

An example of a plugin handler might be (in Lua):

<code> 
function OnPluginBroadcast (msg, id, name, text)
  Note ("msg = " .. msg)
  Note ("id = " .. id)
  Note ("name = " .. name)
  Note ("text = " .. text)
end
</code> 

The calling plugin ID and name are supplied so that plugin writers can verify which plugin originated a particular message. This cannot be spoofed as it is supplied automatically by MUSHclient.


<code> 
<b>OnPluginTrace</b>
</code>

This is called when you have tracing turned on. If a plugin is found with this function in it, then it is called and the trace line is not displayed on the world output window. Only the first plugin found is called.

Example, in Lua:

<code> 
function OnPluginTrace (line)
  AppendToNotepad ("Trace", line .. "\r\n")
end
</code> 


<code> 
<b>OnPluginScreendraw </b>
</code>

This is intended for people with screen readers, who want the contents of the main window read out, however don't want gagged text to be read. The current way MUSHclient works is to draw text as it arrives, and then "undraw it" if it is gagged. This approach doesn't really work with screen readers, as they can't "unread" something.

The arguments to OnPluginScreendraw are:

Type: type of line, where 0 = output line, 1 = note, 2 = command

Log: are we planning to log it?

Line: the text of the line itself

An example plugin function, which simply copies the text to a notepad window, is as follows:

<code> 
function OnPluginScreendraw (type, log, line)
  AppendToNotepad ("mylog", type, " ", log, " ", line, "\r\n")
end -- function
</code> 

<code> 
<b>OnPluginDrawOutputWindow</b>
</code>

This is intended to allow plugin writers to make a miniwindow that has text that scrolls with the output window. It is called at the start of drawing (refreshing) the output window (eg. when a new line arrives from the MUD, or after a Note).

The arguments to OnPluginDrawOutputWindow are:

FirstLine: The first line number which is going to be drawn (starting at 1). You can use GetLineInfo to get details about that line.

ScrollOffset: The pixel position which it will start drawing at (based on the scroll bar thumb position). You can use that to tweak which pixel to start drawing at vertically.

NotUsed: An empty string (required because of the way plugin callbacks are implemented).

Example of echoing the line number in the output buffer, plus the text of the line is:

<code> 
function OnPluginDrawOutputWindow (firstline, offset, notused)
  local background_colour = ColourNameToRGB ("lightgray")
  local text_colour = ColourNameToRGB ("green")
  local main_height = GetInfo (263)
  local font_height = GetInfo (212)

  -- clear window  
  WindowRectOp (win, miniwin.rect_fill, 0, 0, 0, 0, background_colour)

  -- allow for scrolling position
  local top =  (((firstline - 1) * font_height) - offset) - 2

  -- how many lines to draw
  local lastline = firstline + (main_height / font_height)
  
  for line = firstline, lastline do
    if line >= 1 and GetLineInfo (line, 1) then
      WindowText (win, font, line .. ": " .. GetLineInfo (line, 1), 0, top, 
                  0, 0, text_colour)
      top = top + font_height  
    end -- if line exists
  end -- for each line
  
end -- OnPluginDrawOutputWindow
</code> 

Do <b>not</b> call WindowCreate inside this callback or strange things may happen as it is in the middle of drawing to the output device context. Reserve creating the window for OnPluginInstall and OnPluginWorldOutputResized.

Do <b>not</b> call Repaint inside this callback or the client will go into an infinite loop (it is already repainting the window, so trying to repaint it while repainting it will cause a loop). Also do not do things like print to the output window (eg. using Note) as that will cause the output window to be redrawn, and then the callback will be called again, and so on.


<code> 
<b>OnPluginPlaySound</b>
</code>

This is called when MUSHclient intends to play a sound (eg. new activity sound, trigger sound, world.Sound script function). If it finds a plugin with the OnPluginPlaySound function defined, then that is called, and the internal sound-player is not used. The only argument is the sound file name that is to be played.

<code> 
function OnPluginPlaySound (sound)
  Note ("Playing sound ", sound)
end -- function
</code> 

If you select the Display &gt; Stop Sound Playing menu item, then OnPluginPlaySound will be called with an empty file name.

<code> 
<b> OnPluginWorldOutputResized </b>
</code>

This is called when the output window is resized.

<code> 
function OnPluginWorldOutputResized ()
  -- do something here
end -- function
</code> 


<code> 
<b> OnPluginMouseMoved </b>
</code>

This is called when the mouse is moved inside the output window.

<code> 
function OnPluginMouseMoved (x, y, mw)
  -- do something here
  return 0
end -- function OnPluginMouseMoved
</code> 

The x and y arguments (long integers) give the location of the mouse, relative to the top-left corner of the current world's output window. 

The third argument is the miniwindow ID of any miniwindow the mouse may happen to be over, or "" if it is not over a miniwindow.

<code> 
<b> OnPluginTick</b>
</code>

This is called 25 times a second.


<code> 
function OnPluginTick ()
  -- do something here
  return 0
end -- function OnPluginTick
</code> 

This is called 25 times a second (every 40 milliseconds), even if timers are disabled.

It is intended as a simple way of doing things that need to be done smoothly and more rapidly than timers allow (timer granularity is set to a minimum of 1/10 of a second). For example, when using the sound functions such as PlaySound, you could smoothly fade music up or down using this callback.

Also you might use it to implement scrolling text (eg. a miniwindow that says "Critical Hit!") which smoothly scrolls up the screen and disappears. The callback is called 25 times a second as 25 fps (frames per second) is about the minimum for smooth animation, so animated effects (like scrolling text) should look reasonably smooth if implemented using this.

<b>Warning!</b> This is implemented using a Windows timer event (WM_TIMER). This is a low-priority event, which means it may not be called if other things are happening. In other words, the timer may fire less frequently than 25 times a second, depending on what else is happening.

<code> 
<b>OnPluginTelnetRequest</b>
</code>

This is called if the server sends IAC WILL x, or IAC DO x to the client. In that case the callback lets you decide whether or not to handle the protocol (eg. ATCP or ZMP). The following protocols are handled internally and may not cause a call to this function (in some cases for DO and in some cases for WILL):

  1 (ECHO)     - output echo on/off
  3 (SGA)      - Suppress Go Ahead
 24 (TERMTYPE) - send terminal type
 25 (EOR)      - End Of Record
 31 (NAWS)     - Negotiate About Window Size
 70 (MSSP)     - MUD Server Status Protocol
 85 (MCCP v1)  - MUD Client Compression Protocol version 1
 86 (MCCP v2)  - MUD Client Compression Protocol version 2
 91 (MXP)      - MUD eXtension Protocol
102 (Aardwolf options)  - used by Aardwolf MUD and some MUSHclient plugins

If you return <b>true</b> then MUSHclient will send a positive response to the server <b>and then</b> call OnPluginTelnetRequest a second time with another code, as follows:

If it initially called the plugin with "WILL" it will call back with "SENT_DO". 
If it initially called the plugin with "DO" it will call back with "SENT_WILL". 

This is because the positive response to WILL is DO, and the positive response to DO is WILL. This second call to OnPluginTelnetRequest lets you do extra processing after agreeing to the negotiation with the server, such as logging on to it.

The OnPluginTelnetRequest function should return true to indicate it handled the message, or false if it did not. Once OnPluginTelnetRequest returns true in one plugin, no further plugins are checked. This is to stop multiple plugins logging in, as presumably a single login is all that is required.

<code> 
function OnPluginTelnetRequest (type, data)

  if type == 200 and data == "WILL" then
    return true
  elseif type == 200 and data == "SENT_DO" then
    -- IAC SB 200 response IAC SE 
    SendPkt ("255250200Server.Logon Nick255240")  -- example only
  end -- if

end -- function OnPluginTelnetRequest
</code> 

<code> 
<b>OnPluginTelnetSubnegotiation</b>
</code>

This is called if the server sends IAC SB x &lt;data&gt; IAC SE to the client. In that case the callback lets you handle the protocol yourself. The following types are not sent as they are handled internally.

24 (terminal type)
42 (charset)
85 (MCCP v1)
86 (MCCP v2)
91 (MXP)

In the case of type 102, then OnPluginTelnetOption is called <b>as well</b> (without the option number, as that is fixed at 102). 

<code> 
function OnPluginTelnetSubnegotiation (type, data)
  Note ("received negotiation: ", telnet_option)
  Note ("Received option string ", utils.tohex (data))
end -- function OnPluginTelnetSubnegotiation
</code> 

<b>Note</b> - despite the above example, it is not recommended that you do Notes (or anything similar) when receiving telnet subnegotiation packets. Doing a Note may switch the current line from "MUD output" to "Note line" in ways that are not expected, particularly if you are hoping to trigger on the next line that arrives.


<code> 
<b>OnPluginTelnetOption</b>
</code>

This is called if the server sends IAC SB 102 &lt;data&gt; IAC SE to the client. In that case the callback lets you handle the protocol yourself. This is similar to OnPluginTelnetSubnegotiation but is included separately for backwards compatibility. Note that OnPluginTelnetSubnegotiation is <b>also</b> called (afterwards), so new scripts can just use OnPluginTelnetSubnegotiation.

<code> 
function OnPluginTelnetOption (data)
  Note ("Received option string ", utils.tohex (data))
end -- function OnPluginTelnetOption
</code> 




<code> 
<b>OnPlugin_IAC_GA</b>
</code>

This is called if the server sends IAC GA (0xFF 0xF9) or IAC EOR (0xFF 0xEF) to the client. This is intended for situations like where the ATCP protocol sends a whole lot of telnet negotiation sequences, and then IAC GA when waiting for player input. In this case the IAC GA could be a signal to a plugin to start responding.

<code> 
function OnPlugin_IAC_GA ()
  -- respond to server
end -- function OnPlugin_IAC_GA
</code> 


<hr/>
<b>Chat System Callbacks</b>

<code>
<b>OnPluginChatAccept</b>

--  MUSHclient has received a connection from IP,name
--  Return TRUE to accept it, FALSE to reject it
--
function OnPluginChatAccept (sText)

local username, ip = string.match (sText, "(.-),(.+)")

end -- function

<b>OnPluginChatMessage</b>

--  MUSHclient has received chat message: id, message, text
--  Return TRUE to use the default processing, FALSE to ignore it
--
--  The message code indicating the chat message, where these are likely
--         to be received:
--

--   1    Name_change				  
--   2    Request_connections 
--   3    Connection_list	 		
--   4    Text_everybody			
--   5    Text_personal			  
--   6    Text_group				  
--   7    Message					    
--   8    Do_not_disturb			
--   9    Send_action				  
--  10    Send_alias				  
--  11    Send_macro				  
--  12    Send_variable				
--  13    Send_event			    
--  14    Send_gag				    
--  15    Send_highlight			
--  16    Send_list				    
--  17    Send_array				  
--  18    Send_baritem			  
--  19    Version					    
--  20    File_start				  
--  21    File_deny				    
--  22    File_block_request	
--  23    File_block			    
--  24    File_end				    
--  25    File_cancel				  
--  26    Ping_request				
--  27    Ping_response				
--  28    Peek_connections		
--  29    Peek_list			    	
--  30    Snoop					      
--  31    Snoop_data		
-- 105    Send_command		  


function OnPluginChatMessage (id, message, sText)
  return true -- process it
end -- function

<b>OnPluginChatMessageOut</b>

--  MUSHclient is about to send chat message: id, message, text
--  Return TRUE to use the default processing, FALSE to ignore it
--
--  See above for the exact message numbers that might be sent.

function OnPluginChatMessageOut (id, message, sText)
  return true -- process it
end -- function

<b>OnPluginChatDisplay</b>

--
--  MUSHclient is about to display message: message, text
--  Return TRUE to use the default display, FALSE to not display
--
--  See above for the exact message types that might be received.
--

function OnPluginChatDisplay (message, sText)
  return true -- display it
end -- function

<b>OnPluginChatNewUser</b>

--
-- A new chat user has been accepted on: id, name
--
--
-- This script callback has been provided so you can take action if
-- you want (such as allowing file transfers).
--

function OnPluginChatNewUser (id, name)
end -- function

<b>OnPluginChatUserDisconnect</b>

-- This chat user has disconnected for one reason or another.
--
-- This callback lets you take action (eg. notify others) however
-- you cannot send messages to this connection or change any options
-- once they have disconnected. The chat id is supplied so you can 
-- match the id to the one that connected.
--
-- For each call to OnPluginChatNewUser there should eventually be a
-- corresponding call to OnPluginChatUserDisconnect.
--
function OnPluginChatUserDisconnect (id, name)
end -- function
</code>


doc_name: Arrays
title: Arrays
wiki_name: MushClientArrays
description:
MUSHclient offers internal &quot;key/value pairs&quot; which it calls arrays.

You can have any number of arrays for each world, and also for each plugin. 

Each array has an alphanumeric name (eg. &quot;spells&quot;).

Inside each array is any number of key/value pairs (eg. mana = 22).

Script routines let you add, delete, import, and export from arrays into string variables. You can also enumerate (get a list of) all known arrays, or all keys in a particular array.

These functions are available from version 3.46 onwards.

<b>Array and key names</b>

Each array (eg. &quot;spells&quot;) and each array item key (eg. &quot;cold&quot;) has a name. The name <b>is</b> case-sensitive, and is stored exactly &quot;as is&quot; (no spaces are removed, for example). You can use any (8-bit) character for array and key names except for the &quot;nul&quot; character (hex 00).

Array and key names are unique, so if you have an array, and put something into key &quot;a&quot;, and then something else into key &quot;a&quot;, the original contents will be replaced.

<b>Numeric array and key names</b>

In order to allow arrays to be used as straight numeric sequences, numeric keys are treated specially. If an array or key name consists entirely of numbers, with an optional leading + or - sign, then the name is converted to a number and sorted into numeric order, rather than alpanumeric order. Numeric keys are sorted before all other keys.

Thus, the keys &quot;1&quot;, &quot;0001&quot;, &quot;+1&quot; are all considered the same.


doc_name: spellcheck
title: Spell checker
wiki_name: spellcheck
description:
MUSHclient has an inbuilt spell checker (supplied as a separate DLL file).

You can use this in various ways:

<ul>
<li/> Spell check each command automatically before it is sent

<li/> Spell check commands on request (by keystroke or menu option)

<li/> Spell check arbitrary text from scripting

<li/> Spell check the command window on request from scripting
</ul>


doc_name: lua
title: Lua script extensions
wiki_name: Lua
description:
MUSHclient has some scripting extensions which are only available to Lua scripting. This page describes them.

<hr/>

<b>Lua "sandbox"</b>

To help block out dangerous functions, for example:

<code>
os.execute "del mushclient.exe"
</code>

... MUSHclient has a 'preliminary script' box in its Global Preferences -&gt; Lua section. 

Into this you can place code that disables some 'dangerous' functions (like 'os') by setting them to nil.


The code in this box is executed every time the Lua script engine is instantiated, in other words for every world, and every plugin.

You can modify the sandbox code to remove all restrictions, add more, or fine-tune them to your requirements. For example, if you wanted to use os.date and os.time (and others), but not os.execute, os.remove or os.rename, you could use:

<code>
os.execute = nil  -- no executing OS commands
os.remove = nil   -- no removing files
os.rename = nil   -- no renaming files
</code>

<hr/>

<b>'print' function</b>

To make it easier to use Lua examples in MUSHclient, the function "print" is defined to effectively call the world "Note" function. However, unlike Note, print adds a space between each argument (like the Lua "print" does).

eg. 

<code>
Note "hello, world"
print "hello, world"    --&gt; does the same thing

Note (1, 2, 3) --> 123
print (1, 2, 3) --> 1 2 3
</code>

<hr/>

<b>world functions available from global scope</b>

Although the normal MUSHclient script functions are defined in the "world" table, MUSHclient adds a metatable to the _G table and uses the __index entry to make the script functions available at global scope.

Put another way, you can either write:

<code>
world.Note "hello, world"  --&gt; calls Note function in world table

Note "hello, world"        --&gt; does the same thing
</code>

Both methods call the world.Note script function.

If you wish to change the behaviour of an inbuilt script function you must replace the world.XXX version (eg. change world.Note) rather than simply replacing the global version.

<hr/>

<b>'check' function</b>

Many script functions return error codes (see the error_code table described below). A quick way of checking that the function has succeeded is to wrap the 'check' function around it.

For example, instead of:

<code>
DoAfter (10, "eat food")
</code>
you could do this:
<code>
check (DoAfter (10, "eat food"))
</code>

This raises an error (and shows the appropriate error message) if the function fails. Note that this is not relevant to <b>all</b> functions, only those which are documented to return eOK on success, and some other code on failure.

<hr/>

<b>Constants</b>

To make it easier to write scripts, MUSHclient's Lua interface has various built-in tables of constants.


<b>Trigger flags for AddTrigger</b>

These are in the 'trigger_flag' table.

<code>
print (trigger_flag.OmitFromOutput) --&gt; 4
</code>

<b>Trigger flags for AddAlias</b>

These are in the 'alias_flag' table.

<code>
print (alias_flag.AliasQueue) --&gt; 4096
</code>

<b>Trigger flags for AddTimer</b>

These are in the 'timer_flag' table.

<code>
print (timer_flag.OneShot) --&gt; 4
</code>

<b>Custom colour flags for AddTrigger</b>

These are in the 'custom_colour' table.

<code>
print (custom_colour.NoChange) --&gt; -1
</code>

<b>Error codes - map error names to numbers</b>

These are in the 'error_code' table.

You can use these to check individual error codes.

eg.

<code>
if AddTimer (blah blah blah) == 
     error_code.eTimerAlreadyExists  then
  error ("That timer already exists")
end
</code>

<code>
print (error_code.eBadRegularExpression) --&gt; 30021
</code>

Also see above about the 'check' function.


<b>Error codes - map error codes to descriptions</b>

These are in the 'error_desc' table.

You can use these to give meaningful error messages.

eg.

<code>
status = AddTimer ("a", 0, 0, 0, 0, 0)
if status ~= error_code.eOK  then
  error (error_desc [status]) --&gt;  Time given to AddTimer is invalid
end
</code>

<b>Colour names - map colour picker names to RGB values</b>

These are in the 'colour_names' table.

You can use these to look up colour names (eg. "red") and find the corresponding RGB value.


<b>Extended colour codes - map colour selector numbers to RGB values</b>

These are in the 'extended_colours' table.

You can use these to see what the RGB equivalent is for the 256 extended colours (keyed by 0 to 255).


<b>Send-to codes - map scripted "send" names to a number</b>

These are in the 'sendto' table.

You can use these to make functions like DoAfterSpecial more self-documenting. For example, instead of sending to '12', you can send to 'sendto.script'.

eg.

<code>
DoAfterSpecial (5, "Sound ('ding.wav')",  sendto.script)
</code>

<b>Miniwindow constants</b>

These are in the 'miniwin' table.

You can use these to make functions like WindowCreate, WindowRectOp, WindowCircleOp etc. more self-documenting. For example, instead of doing WindowRectOp action 1, you can use 'miniwin.rect_frame'.

eg.

<code>
WindowRectOp (win, miniwin.rect_frame, 20, 20, 70, 70, ColourNameToRGB("blue")) 
</code>


<hr/>

<b>progress</b>

This provides functionality for displaying a "progress" dialog box during lengthy operations.

First you create the progress dialog with:

progress.new (description)

That returns a userdata item that you can then use in subsequent operations:

<code>
dlg:status (msg) --&gt; set a status message (eg. "processing 'foo' ")
dlg:range (low, high) --&gt; sets the range of operations (eg. 1 to 100)
dlg:position (pos)  --&gt; sets where we are in the range (eg. 80)
dlg:checkcancel ()  --&gt; returns true if the user clicked on the cancel button
dlg:setstep (amount)  --&gt; sets the step amount (eg. 5)
dlg:step ()  --&gt; increase the position by the step amount
dlg:close ()  --&gt; dismiss the progress dialog
</code>

Example of use:

<code>
local dlg = progress.new ("Loading things ...")
dlg:range (0, 3)  --&gt; 3 steps
dlg:setstep (1)  --&gt; step 1 per step
dlg:status ("Processing foo")  --&gt; first step
dlg:step ()
-- do something lengthy here
dlg:status ("Processing bar")  --&gt; second step
dlg:step ()
-- do something lengthy here
dlg:status ("Processing fruit")  --&gt; third step
dlg:step ()
-- do something lengthy here
dlg:close ()  --&gt; all done
</code>

The dialog box is a "modal" dialog, so make sure you arrange to close it, even on a script error, or it will lock out attempts to use the GUI interface. If necessary, use "pcall" on whatever it is you do while the dialog is open.


doc_name: lua_bc
title: Lua bc (big number) functions
wiki_name: LuaBc
description:
<b>Big number (bc) functions</b>

This library lets you do arbitrary precision (big number) arithmetic.

Big numbers have a metatable attached to them so you can add, subtract, divide, multiply, raise to a power, and compare them in the usual way. You can also use bc.add, bc.sub, bc.div, bc.mul, and bc.pow to do the same operations.

Thus, the following two forms are equivalent:

<code>
bc.digits (20)
a = bc.number (2)
print (bc.sqrt (a))  --&gt; 1.41421356237309504880
print (a:sqrt ())    --&gt; 1.41421356237309504880
</code>

Also see:

<ul>
<li/>The math library for other mathematical operations.
<li/>The bit library for bitwise operations.
</ul>

Some useful constants are:

<code>
           
 e = 2.7182818284590452353602874713526624977572470936999595749669676277240766303535

pi = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862

radians = degrees * pi / 180
</code>


doc_name: miniwindows
title: MiniWindows
wiki_name: miniwindows
description:
MUSHclient from version 4.34 onwards now has "floating miniwindows" which appear on top of, or to the side of, the main output window. As these are part of the main window, if you move or resize the main window, the extra windows automatically move with it.

You can use the TextRectangle function to move the main scrolling output window away from the edges of the window, so that miniwindows can be placed above, below, or to the sides of the text, without overlapping it.

<ul>
<li/>Miniwindows are created and manipulated purely by script commands, generally intended to be inside plugins.

<li/>You can have any number of miniwindows at once. Each one has a name which is used by the script to refer to it. Your only limitation would be available screen space, and your imagination. Names are case-sensitive.

<li/>Miniwindows do not necessarily have to be visible. Thus you could be adding to a miniwindow (such as your inventory) during combat, when you might not want to see it. Later, you can show it, and its most recent contents will be displayed.

<li/>Each miniwindow is rectangular in shape, and can be any size you like. They start off with a background colour you specify, however you can change that partly or completely by drawing in the window.

<li/>You can position the miniwindows whereever you want to, however there are various auto-positioning options, such as top left corner, middle of top of window, top right corner, and so on.

<li/>Miniwindows are drawn in an off-screen buffer (bitmap), and then automatically copied to the main output window, whenever the output window is redrawn. This provides fast, flicker-free operation.

<li/>Miniwindows can be drawn either above or below the normal output window text. Normally for a floating-style window you would want it above (and thus the text scrolls underneath it), however for some background information you can choose to have the text scroll over the miniwindow.

<li/>Miniwindows can capture mouse-down, mouse-move, and mouse-up events, in order to react to the player clicking on them. This can be used to implement hyperlinks, buttons, and "mouse-over" help.

<li/>Miniwindows can be resized and moved as desired.

<li/>Miniwindows can be drawn transparently, so that they can have holes in them, wherever the transparent colour appears.

<li/>Miniwindows can have any number of "hotspots" which are rectangular areas which react to mouse-over, mouse-down, and mouse-up events. Each hotspot has a "hotspot ID" which identifies it. Hotspot IDs are case-sensitive. Hotspots can optionally show "hover-over" text (eg. hints) to show what they are used for.

<li/>With the assistance of some scripting (see the "movewindow" module) you can arrange for miniwindows to be dragged around to any desired location.
</ul>


doc_name: lua_rex
title: Lua PCRE regular expression functions
wiki_name: LuaRex
description:
<b>PCRE regular expression functions (rex)</b>

The functionality of the PCRE (Perl Compatible Regular Expression) library is available to Lua scripts.

This is exactly the same regular expression matching that is done in triggers and alias matching.

First you create (compile) a regular expression into a rex object using rex.new.

Once the object is compiled you can repeatedly match it against target strings using re:match, re:gmatch, and re:exec (where "re" is the name of the compiled object).


doc_name: lua_syntax
title: Lua syntax
wiki_name: LuaSyntax
description:
<b>Lua general syntax</b>

This section summarizes the syntax of Lua.

For more details see the online Programming In Lua book:

<code>http://www.lua.org/pil/</code>

Note that Lua is case-sensitive. Thus <b>TRUE</b> and <b>true</b> are different things.

There are a lot of examples and discussions in the Lua part of the MUSHclient forum:

<code>http://www.mushclient.com/lua</code>

<hr/>


doc_name: lua_base
title: Lua base functions
wiki_name: LuaBase
description:
<b>Lua base functions and variables</b>

These are the "base" functions in Lua (that is, those that are not in library tables).

<hr/>

<b>_G</b>

Variable which is the global environment table. (_G._G == _G)
You cannot change the environment by assigning to _G, use setfenv instead.

<b>_VERSION</b>

A global variable that is a string containing the current Lua interpreter version.

<code>
print (_VERSION) --&gt; Lua 5.1
</code>


doc_name: lua_string
title: Lua string functions
wiki_name: LuaString
description:
<b>Lua string functions</b>

These are the functions in the "string" table.

Indices, where used, start at 1 for the first character (not zero). Negative numbers count from the right, so -1 is the last character, -2 the second last, and so on. 

All strings have a metatable added to them by Lua with an __index entry pointing to the string table. What this means is that you can write string function calls in two ways:

<code>
s = "hello, world"
string.len (s) --&gt; 12
s:len ()       --&gt; 12
</code>

The second version is shorter as the word "string" is implied. Note the colon after the s, not a dot.


doc_name: lua_coroutines
title: Lua coroutine functions
wiki_name: LuaCoroutines
description:
<b>Lua coroutine functions</b>

These are the functions in the "coroutine" table.

Coroutines are a very powerful way of splitting execution of a function up until some event occurs (for example, a timer fires, or input arrives). The function chooses when to "yield" execution.

The yield / resume sequence allows variables to be passed back and forward between the thread and the caller. For example the thread can yield with an argument which tells the caller why it yielded, and the caller can resume with an argument telling the thread why it was resumed.

Personally I wouldn't use coroutine.wrap, but stick to something like this:

<ul>
<li/>Create a new thread using coroutine.create. At this stage it is not yet running.
<li/>Commence executing the function in the thread with coroutine.resume, passing any initial arguments required.
<li/>The thread yields execution, if necessary, using coroutine.yield, passing arguments back to be returned by coroutine.resume. These arguments could indicate the reason for yielding.
<li/>The main script resumes the thread when it is ready to do so, calling coroutine.resume again. This time arguments passed to coroutine.resume are returned as results from the coroutine.yield call. These arguments could indicate the reason the thread is resuming (eg. data received, timeout and so on).
<li/>The previous 2 steps are repeated until it is time for the function to return, effectively terminating the thread.
</ul>


doc_name: lua_tables
title: Lua table functions
wiki_name: LuaTables
description:
<b>Lua table functions</b>

These are the functions in the "table" table.

Tables are collections of key/value pairs, where both the key and the value can be any Lua data type, except nil. 

Tables are indexed by the key, so if you know the key you can quickly retrieve the value. If you don't know the keys you can search the table using the "pairs" or "ipairs" functions.

Since keys and values can be any data type (except nil) it follows that tables can contain other tables.

A table's size (which is only relevant for numerically-indexed tables) is one less than the first integer index with a nil value. If the table has "holes" in it - that is, numeric keys with gaps in the sequence - then the table size is not guaranteed to be the the last gap. Lua does a binary search to try to find a gap, it does not necessarily find the first or last one.

If you are planning to treat your tables as vectors (that is, with numeric keys and a size) then we recommend that you do not allow gaps in the sequence.

If you want to know if a table is empty, or not, you can test:

<code>
if next (t) == nil then
  -- table t is empty
end -- if empty
</code>

The behaviour of tables can be modified somewhat by attaching a "metatable" to them with the setmetatable function.


doc_name: lua_sqlite3
title: Lua SQLite (database) interface
wiki_name: LuaSqlite3
description:
LuaSQLite 3 is a thin wrapper around the public domain SQLite3 database engine.

The lsqlite3 module supports the creation and manipulation of SQLite3 databases. The exported functions are called with prefix sqlite3. However, most sqlite3 functions are called via an object-oriented interface to either database or SQL statement objects.

This documentation does not attempt to describe how SQLite3 itself works, it just describes the Lua binding and the available functions. 

For more information about the SQL features supported by SQLite3 and details about the syntax of SQL statements and queries, please see the SQLite3 documentation http://www.sqlite.org/. 

Using some of the advanced features (how to use callbacks, for instance) will require some familiarity with the SQLite3 API.

<b>General technique</b>

<ul>
<li/>Open the database with either sqlite3.open or sqlite3.open_memory

<li/>Execute "action" SQL statements with db:exec

<li/>To query data from the database:
<ul>

<li/>Prepare an SQL statement with db:prepare
<li/>Get column names with stmt:get_names or similar
<li/>Step through each row with stmt:step
<li/>Get column values with stmt:get_values or similar
<li/>After all rows are extracted, finalize the statement with stmt:finalize
</ul>

<li/>Close the database with db:close



</ul>


<hr/>

<b>Numerical error and result codes</b>

The following constants are defined by module sqlite3:

<code>
  OK: 0          ERROR: 1       INTERNAL: 2    PERM: 3        ABORT: 4
  BUSY: 5        LOCKED: 6      NOMEM: 7       READONLY: 8    INTERRUPT: 9
  IOERR: 10      CORRUPT: 11    NOTFOUND: 12   FULL: 13       CANTOPEN: 14
  PROTOCOL: 15   EMPTY: 16      SCHEMA: 17     TOOBIG: 18     CONSTRAINT: 19
  MISMATCH: 20   MISUSE: 21     NOLFS: 22      FORMAT: 24     RANGE: 25
  NOTADB: 26     ROW: 100       DONE: 101
</code>

For details about their exact meaning please see the SQLite3 documentation http://www.sqlite.org/.


doc_name: lua_math
title: Lua math functions
wiki_name: LuaMath
description:
<b>Lua math functions</b>

These are the functions in the "math" table.

Trigonometry functions use radians. To convert degrees to radians use math.rad.
Or, to look at it another way: 

<code>
radians = degrees * math.pi / 180
</code>

<b>pi</b>

The variable math.pi gives you the value of pi.

<code>
pi = math.pi
</code>

<b>e</b>

To use e in an expression you can use the math.exp function.

<code>
e = math.exp (1)
</code>

See also the "bc" (big number) library for functions that work with numbers to arbitrary precision.


doc_name: lua_io
title: Lua io functions
wiki_name: LuaIo
description:
<b>Lua io functions</b>

These are the functions in the "io" table.

Implicit operations (eg. io.read, io.write) use the standard file descriptors io.stdin, io.stdout, and io.stderr.

You can operate on other files by getting a "file descriptor" from io.open,  io.input, or io.output, and using that.

Note the syntactical difference, that you follow a file descriptor by a colon, eg. f:close ()

Also see the description for the "os" table for operating system functions that do things like remove and rename files.

<hr/>

The operations whose name start with "f:" (such as f:read) depend on having an open file handle returned from io.open, io.input, or io.output.

Note the colon after the f, as this indicates that the file handle (userdata from the open) is to be supplied as the first argument to the function.


doc_name: lua_os
title: Lua os functions
wiki_name: LuaOs
description:
<b>Lua os functions</b>

These are the functions in the "os" table. Some of these functions are disabled by default in the MUSHclient "Lua sandbox". Check that out if you plan to use the "os" functions.


doc_name: lua_debug
title: Lua debug functions
wiki_name: LuaDebug
description:
<b>Lua debug functions</b>

These are the functions in the "debug" table. The debug functions are not optimized for speed, they are designed to help debug your programs.


doc_name: lua_utils
title: Lua utilities
wiki_name: LuaUtils
description:
The "utils" (utilities) library offers various helpful utility functions, including:

<ul>
<li/>Bringing a different program window to the front
<li/>Compression and decompression
<li/>Hashing using various methods
<li/>Base-64 encoding and decoding
<li/>Dialog boxes for asking questions and making announcements
<li/>Dialog boxes for choosing from lists and combo-boxes
<li/>Executing Windows "shell" commands
<li/>File-picker dialog box
<li/>Spell-checker "misspelt word" dialog box
<li/>Spell-checker utilities such as metaphone and edit distance
<li/>Conversion of strings to and from hexadecimal form
<li/>Read disk directory into a table
<li/>Information about MUSHclient environment (directory names)
<li/>List of world function names
<li/>List of plugin callback function names
<li/>Split a string into a table, at delimiters (eg. comma-delimited)
<li/>UTF-8 (Unicode) encoding, decoding and checking
<li/>XML parser
</ul>

See also the following libraries:

<ul>
<li/>Perl-compatible regular expressions library (rex)
<li/>Big number (arbitrary precision) library (bc)
<li/>Bit management library (bit)
</ul>

You can also use the luacom library (to access COM objects). To do this you must first "require" it, like this:

<code>
require "luacom"
</code>

There is documentation about luacom in a PDF document in the MUSHclient docs subdirectory.


doc_name: database
title: Database (SQLite)
wiki_name: database
description:
MUSHclient from version 4.40 onwards has support for accessing SQLite 3 databases.

<ul>
<li/>Databases are created and manipulated purely by script commands, generally intended to be inside plugins.

<li/>You can have any number of databases open at once. Each one has a name which is used by the script to refer to it. 

<li/>Databases can be purely "in memory" by using the filename ":memory:".

</ul>

<b>General technique</b>

<ul>
<li/>Open the database with DatabaseOpen

<li/>Execute "action" SQL statements with DatabaseExec

<li/>To query data from the database:
<ul>

<li/>Prepare an SQL statement with DatabasePrepare
<li/>Get column names with DatabaseColumnName or DatabaseColumnNames
<li/>Step through each row with DatabaseStep
<li/>Get column values with DatabaseColumnValue or DatabaseColumnValues
<li/>After all rows are extracted, finalize the statement with DatabaseFinalize
</ul>

<li/>Close the database with DatabaseClose

</ul>

For more information, see: 

<code>
http://www.gammon.com.au/db
</code>

You can also use the Lua sqlite3 interface to work on SQLite databases, in Lua only.

<hr/>

<b>Example of creating a database</b>

<code>
db = "mainDatabase"  -- internal identifier

DatabaseOpen (db, GetInfo (66) .. "mytestdb.sqlite", 6)

DatabaseExec (db, [[
DROP TABLE IF EXISTS weapons;
CREATE TABLE weapons(
        weapon_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
        name      TEXT NOT NULL,
        damage    INT DEFAULT 10,
        weight    REAL
      );
      ]])
      
DatabaseClose (db)  -- close it
</code>

It is better to check the result from calling functions like DatabaseExec, otherwise they may silently fail (eg, with an SQL syntax error) like this:

<code>
status = DatabaseExec (db, [[
DROP TABLE IF EXISTS weapons;
CREATE TABLE weapons(
        weapon_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
        name      TEXT NOT NULL,
        damage    INT DEFAULT 10,
        weight    REAL
      );
      ]])
      
if status ~= sqlite3.OK then
  print ("Error creating weapons table: ", DatabaseError(db))
end -- if not OK
</code>

The documentation for DatabaseExec suggests a function (dbcheck) which can be used as a generic return-code checker.

<hr/>

<b>Example of adding a row of data</b>

<code>
DatabaseExec (db, "INSERT INTO weapons (name, damage) VALUES ('Nick''s sword', 42)")
</code>

Note that if you need to use quotes inside a string, the quotes must be doubled, as shown above.

<hr/>

<b>Example of selecting some rows and displaying them</b>

As described above, you need to "prepare" the SQL statement first. Once prepared you can find how many columns are in it, and the column names.

Then you "step" through the rows, one by one, getting the column values. These can then be printed, saved, or acted up.

Finally you "finalize" the SQL statement, releasing it so you can do another operation.

<code>
-- prepare a query
DatabasePrepare (db, "SELECT * FROM weapons ORDER BY name")

-- find the column names
names = DatabaseColumnNames (db)

-- find how many columns there are
cols = DatabaseColumns (db)

-- step to get the first row
rc = DatabaseStep (db)  -- read first row

-- now loop, displaying each row, and getting the next one
while rc == sqlite3.ROW do
  
  print ("")
  values = DatabaseColumnValues (db)

  for i = 1, cols do
    print (names [i], "=", values [i])
  end -- for each column

  rc = DatabaseStep (db)  -- read next row

end -- while loop

-- finished with the statement
DatabaseFinalize (db)
</code>

You should really check the return code from DatabasePrepare in case you have an error in the SQL statement, as shown above for DatabaseExec.

<hr/>

<b>Example using the Lua interface</b>

<code>
require "tprint"

-- make in-memory database
db = sqlite3.open_memory()

-- make a table for testing
db:exec  [[
          CREATE TABLE mobs (name, class, hp);
          INSERT INTO mobs VALUES("Naga", "mage", 666);
          INSERT INTO mobs VALUES("Wolf", "beast", 42);
          INSERT INTO mobs VALUES("Guard", "warrior", 100);
       ]]

-- prepare a SELECT statement
local stmt = db:prepare ("SELECT * FROM mobs")

-- loop until we get everything
while true do

  local result = stmt:step ()

  -- exit loop if done
  if result == sqlite3.DONE then
    break
  end -- if done

  -- should have ROW result
  assert (result == sqlite3.ROW, "Row not found")

  -- get all values into a table
  local row = stmt:get_named_values()

  -- display them
  print (string.rep ("-", 20))
  tprint (row)
  
end -- while

-- done with this statement
stmt:finalize ()

-- finished with database
db:close ()
</code>


doc_name: lua_lpeg
title: Lua LPEG library
wiki_name: LuaLpeg
description:
LPeg is a pattern-matching library for Lua, based on Parsing Expression Grammars (PEGs).

 For a more formal treatment of LPeg, as well as some discussion about its implementation, see:

http://www.inf.puc-rio.br/~roberto/docs/peg.pdf  (A Text Pattern-Matching Tool based on Parsing Expression Grammars.)

Following the Snobol tradition, LPeg defines patterns as first-class objects. That is, patterns are regular Lua values (represented by userdata). The library offers several functions to create and compose patterns. With the use of metamethods, several of these functions are provided as infix or prefix operators. On the one hand, the result is usually much more verbose than the typical encoding of patterns using the so called regular expressions (which typically are not regular expressions in the formal sense). On the other hand, first-class patterns allow much better documentation (as it is easy to comment the code, to use auxiliary variables to break complex definitions, etc.) and are extensible, as we can define new functions to create and compose patterns.

For a quick glance of the library, the following table summarizes its basic operations for creating patterns:

<hr/>

<b>Operator	Description</b>

<ul>
<li/>lpeg.P(string) : Matches string literally
<li/>lpeg.P(number) : Matches exactly number characters
<li/>lpeg.S(string)	  : Matches any character in string (Set)
<li/>lpeg.R("xy")	: Matches any character between x and y (Range)
<li/>patt^n	: Matches at least n repetitions of patt
<li/>patt^-n	: Matches at most n repetitions of patt
<li/>patt1 * patt2	: Matches patt1 followed by patt2
<li/>patt1 + patt2	: Matches patt1 or patt2 (ordered choice)
<li/>patt1 - patt2	: Matches patt1 if patt2 does not match
<li/>-patt	: Equivalent to ("" - patt)
<li/>#patt	: Matches patt but consumes no input
</ul>

<hr/>

As a very simple example, lpeg.R("09")^1 creates a pattern that matches a non-empty sequence of digits. As a not so simple example, -lpeg.P(1) (which can be written as lpeg.P(-1) or simply -1 for operations expecting a pattern) matches an empty string only if it cannot match a single character; so, it succeeds only at the subject's end.

In addition to the functions documented here, some arithmetic operators have special effects on patterns:

<hr/>

<b>#patt</b>

Returns a pattern that matches only if the input string matches patt, but without consuming any input, independently of success or failure. (This pattern is equivalent to &amp;patt in the original PEG notation.)

When it succeeds, #patt produces all captures produced by patt.


<b>-patt</b>

Returns a pattern that matches only if the input string does not match patt. It does not consume any input, independently of success or failure. (This pattern is equivalent to !patt in the original PEG notation.)

As an example, the pattern -lpeg.P(1) matches only the end of string.

This pattern never produces any captures, because either patt fails or -patt fails. (A failing pattern never produces captures.)


<b>patt1 + patt2</b>

Returns a pattern equivalent to an ordered choice of patt1 and patt2. (This is denoted by patt1 / patt2 in the original PEG notation, not to be confused with the / operation in LPeg.) It matches either patt1 or patt2, with no backtracking once one of them succeeds. The identity element for this operation is the pattern lpeg.P(false), which always fails.

If both patt1 and patt2 are character sets, this operation is equivalent to set union.


<b>patt1 - patt2</b>

Returns a pattern equivalent to !patt2 patt1. This pattern asserts that the input does not match patt2 and then matches patt1.

If both patt1 and patt2 are character sets, this operation is equivalent to set difference. Note that -patt is equivalent to "" - patt (or 0 - patt). If patt is a character set, 1 - patt is its complement.


<b>patt1 * patt2</b>

Returns a pattern that matches patt1 and then matches patt2, starting where patt1 finished. The identity element for this operation is the pattern lpeg.P(true), which always succeeds.

(LPeg uses the * operator [instead of the more obvious ..] both because it has the right priority and because in formal languages it is common to use a dot for denoting concatenation.)


<b>patt^n</b>

If n is nonnegative, this pattern is equivalent to pattn patt*. It matches at least n occurrences of patt.

Otherwise, when n is negative, this pattern is equivalent to (patt?)-n. That is, it matches at most -n occurrences of patt.

In particular, patt^0 is equivalent to patt*, patt^1 is equivalent to patt+, and patt^-1 is equivalent to patt? in the original PEG notation.

In all cases, the resulting pattern is greedy with no backtracking (also called a possessive repetition). That is, it matches only the longest possible sequence of matches for patt.


<b>patt / string</b>

Creates a string capture. It creates a capture string based on string. The captured value is a copy of string, except that the character % works as an escape character: any sequence in string of the form %n, with n between 1 and 9, stands for the match of the n-th capture in patt. The sequence %0 stands for the whole match. The sequence %% stands for a single %.


<b>patt / table</b>

Creates a query capture. It indexes the given table using as key the first value captured by patt, or the whole match if patt produced no value. The value at that index is the final value of the capture. If the table does not have that key, there is no captured value.


<b>patt / function</b>

Creates a function capture. It calls the given function passing all captures made by patt as arguments, or the whole match if patt made no capture. The values returned by the function are the final values of the capture. In particular, if function returns no value, there is no captured value.


<hr/>

<b>Grammars</b>

With the use of Lua variables, it is possible to define patterns incrementally, with each new pattern using previously defined ones. However, this technique does not allow the definition of recursive patterns. For recursive patterns, we need real grammars.

LPeg represents grammars with tables, where each entry is a rule.

The call lpeg.V(v) creates a pattern that represents the nonterminal (or variable) with index v in a grammar. Because the grammar still does not exist when this function is evaluated, the result is an open reference to the respective rule.

A table is fixed when it is converted to a pattern (either by calling lpeg.P or by using it wherein a pattern is expected). Then every open reference created by lpeg.V(v) is corrected to refer to the rule indexed by v in the table.

When a table is fixed, the result is a pattern that matches its initial rule. The entry with index 1 in the table defines its initial rule. If that entry is a string, it is assumed to be the name of the initial rule. Otherwise, LPeg assumes that the entry 1 itself is the initial rule.

As an example, the following grammar matches strings of a's and b's that have the same number of a's and b's:

<mono>
equalcount = lpeg.P{
  "S";   -- initial rule name
  S = "a" * lpeg.V"B" + "b" * lpeg.V"A" + "",
  A = "a" * lpeg.V"S" + "b" * lpeg.V"A" * lpeg.V"A",
  B = "b" * lpeg.V"S" + "a" * lpeg.V"B" * lpeg.V"B",
} * -1
</mono>


doc_name: lua_bit
title: Lua bit manipulation functions
wiki_name: LuaBit
description:
<b>Bit manipulation functions</b>

The Lua language does not contain native support for bit-wise manipulation of numbers (and, or, exclusive or etc.)

MUSHclient has a few simple extensions that permit that.

They are in the library (table) "bit".


doc_name: lua_package
title: Lua package functions
wiki_name: LuaPackage
description:
<b>Lua package functions</b>

These are the functions in the "package" table.

The package manager is designed for scripters who need to use multiple files and load them in a consistent way. 

See also the "require" and "module" functions in the Lua base functions page.

Some of the items in the package library are strings and tables, rather than functions to be called.


# lua_functions

name: string.byte
prototype: code = string.byte (s, n)
summary: Converts a character into its ASCII (decimal) equivalent
doc_name: lua_string
description:
Returns the ASCII code for the nth character of the string s. The inverse operation is carried out by string.char.

Default for n is 1.

<code>
print (string.byte ("ABC")) --&gt; 65 (A is 65 in ASCII)
print (string.byte ("ABC", 2)) --&gt; 66 (B is 66)
</code>


name: string.char
prototype: s = string.char (n1, n2, n3, ...)
summary: Converts ASCII codes into their equivalent characters
doc_name: lua_string
description:
Receives 0 or more numbers and converts them to the corresponding characters. The inverse operation is carried out by string.byte.

<code>
print (string.char (65, 66)) --&gt; AB
</code>


name: string.dump
prototype: s = string.dump (f)
summary: Converts a function into binary
doc_name: lua_string
description:
Converts a function f into binary representation, which can be subsequently processed by loadstring to retrieve the function. The function must be a Lua function without upvalues.

<code>
function f () print "hello, world" end
s = string.dump (f)
assert (loadstring (s)) () --&gt; hello, world
</code>

Note: this does not currently work if you are using the LuaJIT DLL instead of the one that ships with the normal MUSHclient download. One way of testing for the presence of LuaJIT is to run this:

<code>
print (jit.version) --&gt; LuaJIT 2.0.0-beta7 
</code>

If LuaJIT is not installed you would see something like:

<code>
Error: attempt to index global 'jit' (a nil value)
</code>

Further note: Using string.dump is <b>not recommended</b>. Apart from the issues with LuaJIT it may not be portable across Lua releases or different operating system platforms.


name: string.find
prototype: st, en, cap1, cap2, cap3 = string.find (str, pattern, index, plain)
summary: Searches a string for a pattern
doc_name: lua_string
description:
Find the first match of the regular expression "pattern" in "str", starting at position "index".

The starting position (index) is optional, and defaults to 1 (the start of the string).

If found, returns the start and end position, and any captures as additional results.

If not found, returns nil.

If "plain" is true, the search string is plain text, not a regular expression. (The "plain" argument is optional, and defaults to false).

<hr/>

Also see:

<ul>
<li/><b>string.match</b> which operates in a similar way, but does not return the start and end positions
<li/><b>string.gmatch</b> which iterates over a string, allowing you to take action on each match (eg. on each word)
<li/><b>string.gsub</b> which lets you make replacements on matching elements (for example, replace one word with another, or make certain things all upper-case)
</ul>

<hr/>
<b>Patterns</b>

The standard patterns (character classes) you can search for are:

<code>
 . --- (a dot) represents all characters. 
%a --- all letters. 
%c --- all control characters. 
%d --- all digits. 
%l --- all lowercase letters. 
%p --- all punctuation characters. 
%s --- all space characters. 
%u --- all uppercase letters. 
%w --- all alphanumeric characters. 
%x --- all hexadecimal digits. 
%z --- the character with hex representation 0x00 (null). 
%% --- a single '%' character.
%1 --- captured pattern 1.
%2 --- captured pattern 2 (and so on).
%f[s]  transition from not in set 's' to in set 's'.
%b()   balanced nested pair ( ... ( ... ) ... ) 
</code>

<b>Important!</b> - the uppercase versions of the above represent the complement of the class. eg. %U represents everything <i>except</i> uppercase letters, %D represents everything <i>except</i> digits.

<b>Also important!</b> If you are using string.find (or string.match etc.) in MUSHclient, and inside "send to script" in a trigger or alias, then the % sign has special meaning there (it is used to identify wildcards, for example, %1 is wildcard 1). Thus the % signs in string.find need to be doubled or they won't work properly (so use %%d instead of %d in "send to script"). This does not apply if you are scripting in a script file, because the expansion of wildcards does not apply there.

<hr/>
<b>Magic characters</b>

There are some "magic characters" (such as %) that have special meanings. These are:

<code>
^ $ ( ) % . [ ] * + - ? 
</code>

If you want to use those in a pattern (as themselves) you must precede them by a % symbol.

eg. %% would match a single %  (also see note above about "send to script")

In practice, it is safe to put % in front of any non-alphanumeric character. If in doubt, put a % in front of a special character.

<hr/>
<b>Quotes and backslashes</b>

The arguments to string.find (and string.match, etc.) are just normal Lua strings. Thus, to put a backslash or quote inside such a string you still need to "escape" it with a backslash in the usual way.

eg. string.find (str, "\\")  -- find a single backslash

<hr/>
<b>Sets</b>

You can build your own pattern classes (sets) by using square brackets, eg.

<code>
[abc] ---&gt; matches a, b or c
[a-z] ---&gt; matches lowercase letters (same as %l)
[^abc] ---&gt; matches anything except a, b or c
[%a%d] ---&gt; matches all letters and digits
[%a%d_] ---&gt; matches all letters, digits and underscore
[%[%]] ---&gt; matches square brackets (had to escape them with %)
</code>

You can use pattern classes in the form %x in the set. If you use other characters (like periods and brackets, etc.) they are simply themselves.

You can specify a range of character inside a set by using simple characters (not pattern classes like %a) separated by a hyphen. For example, [A-Z] or [0-9]. These can be combined with other things. For example [A-Z0-9] or [A-Z,.].

The end-points of a range must be given in ascending order. That is, [A-Z] would match upper-case letters, but [Z-A] would not match anything.

A hyphen at the start or end of a set is itself (matches a hyphen).

You can negate a set by starting it with a "^" symbol, thus [^0-9] is everything except the digits 0 to 9. The negation applies to the whole set, so [^%a%d] would match anything except letters or digits. In anywhere except the first position of a set, the "^" symbol is simply itself.

Inside a set (that is a sequence delimited by square brackets) the only "magic" characters are:

<code>
] ---&gt; to end the set, unless preceded by %
% ---&gt; to introduce a character class (like %a), or magic character (like "]")
^ ---&gt; in the first position only, to negate the set (eg. [^A-Z)
- ---&gt; between two characters, to specify a range (eg. [A-F])
</code>

Thus, inside a set, characters like "." and "?" are just themselves.

<hr/>
<b>Repetition</b>

The repetition characters, which can follow a character, class or set, are:

<code>
+  ---&gt; 1 or more repetitions (greedy)
*  ---&gt; 0 or more repetitions (greedy)
-  ---&gt; 0 or more repetitions (non greedy)
?  ---&gt; 0 or 1 repetition only
</code>

A "greedy" match will match on as many characters as possible, a non-greedy one will match on as few as possible.

<hr/>
<b>Anchor to start and/or end of string</b>

The standard "anchor" characters apply:

<code>
^  ---&gt; anchor to start of subject string (must be the very first character)
$  ---&gt; anchor to end of subject string   (must be the very last character)
</code>

For example:

<code>
^You see     ---&gt; string must start with "You see"
experience$  ---&gt; string must end with "experience"
^Tick$       ---&gt; string must be exactly "Tick" with no other characters
</code>

<hr/>
<b>Captures</b>

You can also use round brackets to specify "captures":

<code>
You see (.*) here
</code>

Here, whatever matches (.*) becomes the first capture.

You can also refer to matched substrings (captures) later on in an expression:

<code>
print (string.find ("You see dogs and dogs", "You see (.*) and %1")) --&gt; 1 21 dogs
print (string.find ("You see dogs and cats", "You see (.*) and %1")) --&gt; nil
</code>

This example shows how you can look for a repetition of a word matched earlier, whatever that word was ("dogs" in this case).

As a special case, an empty capture string returns as the captured pattern, the position of itself in the string. eg.

<code>
print (string.find ("You see dogs and cats", "You .* ()dogs .*")) --&gt; 1 21 9
</code>

What this is saying is that the word "dogs" starts at column 9.

There is a limit of 32 captures that can be returned.

<hr/>
<b>Balanced sequences</b>

Finally you can look for nested "balanced" things (such as parentheses) by using %b, like this:

<code>
print (string.find ("I see a (big fish (swimming) in the pond) here",
       "%b()"))  --&gt; 9 41
</code>

After %b you put 2 characters, which indicate the start and end of the balanced pair. If it finds a nested version it keeps processing until we are back at the top level. In this case the matching string was "(big fish (swimming) in the pond)".

<hr/>
<b>Frontier patterns</b>

A "frontier" (or boundary) pattern is used to assert a transition from one set of characters to another (eg. non-letters to letters, or non-digits to digits). This can be useful to detect <b>words</b>, such as "log" but omit "blog" or "logging".

A frontier is specified as %f[set] and matches on a transition from not-in-set to in-set. For example, to match "log" on its own:

<code>
print (string.find ("There is a log here", "%f[%a]log%f[%A]"))   --&gt; 12 14 
print (string.find ("There is a blog here", "%f[%a]log%f[%A]"))  --&gt; nil
print (string.find ("There is logging here", "%f[%a]log%f[%A]")) --&gt; nil
</code>

The first frontier ("%f[%a]") matches on the transition from not-letters to letters. The second frontier ("%f[%A]") matches on letters to not-letters. Effectively this gives you a word boundary match.

<hr/>
<b>Examples</b>

<code>
print (string.find ("the quick brown fox", "quick")) --&gt; 5 9
print (string.find ("the quick brown fox", "(%a+)")) --&gt; 1 3 the
print (string.find ("the quick brown fox", "(%a+)", 10)) --&gt; 11 15 brown
print (string.find ("the quick brown fox", "fruit")) --&gt; nil
</code>


name: string.rep
prototype: s = string.rep (str, n)
summary: Returns repeated copies of a string
doc_name: lua_string
description:
Returns a string which is n copies of the source string concatenated together.

<code>
string.rep ("moo", 4) --&gt; moomoomoomoo
</code>


name: string.format
prototype: s = string.format (fstr, v1, v2, v3, ...)
summary: Formats a string
doc_name: lua_string
description:
Formats the supplied values (v1, v2 etc.) using format string 'fstr', similar to the C function printf.

It is an error to supply too few variables for the format string.

The format string comprises literal text, and directives starting with %. Each directive controls the format of the next argument. Directives can include flags, width and precision controls. To literally incorporate "%" in the output you need to put "%%" in the format string.

For example:

<code>
print (string.format ("To wield the %s you need to be level %i", "sword", 10))

<i>Prints:</i>

To wield the sword you need to be level 10
</code>

In this example the values "sword" and "10" are substituted where the %s and %i appear in the format string.

<b>Important!</b> If you are using string.format in MUSHclient, and inside "send to script" in a trigger or alias, then the % sign has special meaning there (it is used to identify wildcards, such as %1 is wildcard 1). Thus the % signs in string.format need to be doubled or they won't work properly. 

For example:

<code>
print (string.format ("To wield the %%s you need to be level %%i", "sword", 10))
</code>

This does not apply if you are using a separate script file.

<hr/>

<b>Directives</b> can be:

<ul>
<li/>%c - convert a number to a single character (like string.char)

<code>
string.format ("%c", 65) --&gt; A
</code>

<li/>%d and %i - output as an integer number

<code>
string.format ("%i", 123.456) --&gt; 123
</code>

<li/>%o - convert to octal

<code>
string.format ("%o", 16) --&gt; 20
</code>

<li/>%u - convert to an unsigned number

Negative numbers will be converted to 4294967296 (2^32) minus the number.

<code>
string.format ("%u", 1234.566) --&gt; 1234
string.format ("%u", -1234)    --&gt; 4294966062
</code>

<li/>%x - hex (lower-case)

<code>
string.format ("%x", 86543) --&gt; 1520f
</code>

<li/>%X - hex (upper-case)

<code>
string.format ("%X", 86543)--&gt; 1520F
</code>

<li/>%e - scientific notation, "e" in lower case: 

<code>
string.format ("%e", 15) --&gt; 1.500000e+001
</code>

<li/>%E - scientific notation, "E" in upper case: 

<code>
string.format ("%E", 15) --&gt; 1.500000E+001
</code>

<li/>%f - floating point, default to 6 decimal places: 

<code>
string.format ("%f", 15.656e4) --&gt; 156560.000000
</code>

<li/>%g - Signed value printed in %f or %e format, whichever is more compact for the given value. To make it compact, only the required number of decimal places (if any) are shown.

<code>
string.format ("%g", 15.656) --&gt; 15.656
string.format ("%g", 1)      --&gt; 1
string.format ("%g", 1.2)    --&gt; 1.2
</code>

<li/>%G - Same as %g except that an upper-case E is used where appropriate.

<code>
string.format ("%G", 15.656e42) --&gt; 1.5656E+043
</code>


<li/>%q - formats a string in such a way Lua can read it back in (eg. as Lua source).

Basically this means:

<ul>
<li/>It puts a backslash in front of the double quote character (hex 22), backslash itself (hex 5C), and newline (hex 0A).

<li/>The nul character (hex 00) becomes \000

<li/>Carriage return (hex 0D) becomes \r
</ul>

The string itself is surrounded by double quotes.

For example:

<code>
print (string.format ("%q", 'a cat called "Puss"')) --&gt; "a cat called \"Puss\""
</code>

<li/>%s - output a string (or something that can be converted to a string, such as a number).

<li/>%% - output a single % character

</ul>

You can optionally supply 'flags width.precision' arguments before the letter. 

<hr/>

<b>Flags</b> can be:

<ul>
<li/>- : left align result inside field
<li/>+ : always prefix with a sign, using + if field positive
<li/>0 : left-fill with zeroes rather than spaces
<li/>(space) : If positive, put a space where the + would have been
<li/># : Changes the behaviour of various formats, as follows:
For octal conversion (o), prefixes the number with 0 - if necessary.
For hex conversion (x), prefixes the number with 0x
For hex conversion (X), prefixes the number with 0X
For e, E and f formats, always show the decimal point.
For g and G format, always show the decimal point, and do not truncate trailing zeroes.
The option to 'always show the decimal point' would only apply if you had the precision set to 0.
</ul>

<hr/>

<b>Width</b> is the width of the returned field. If the converted number/string is wider than the width it is not truncated. Thus, this is effectively the minimum width. The maximum width you can specify is 99. 

Decimal places are counted in the width, so something like %10.4f will actually have 5 digits before the decimal place. (5 before, plus 1 for the decimal point, plus 4 after adds up to 10).

You cannot use "*" as the width (as you can for printf). If you want variable-size strings you can simulate that by modifying the format string on-the-fly.

eg. instead of %*g, use "%" .. width .. "g"

<hr/>

<b>Precision</b> is the number of decimal places to show for floating-point numbers. The maximum precision you can specify is 99. 

For strings the length of the source string is truncated to the precision size. 

If the precision is omitted it defaults to 6 decimal places for 'e', 'E' and 'f' format types. If decimal places are omitted by the specified precision, the result is rounded.

<hr/>

Examples:

<code>
string.format ("%15.1f", 15.656)   --&gt; '           15.7'
string.format ("%15.8f", 15.656)   --&gt; '    15.65600000'
string.format ("%-15.1f", 15.656)  --&gt; '15.7           '
string.format ("%015.1f", 15.656)  --&gt; '0000000000015.7'
string.format ("%+015.1f", 15.656) --&gt; '+000000000015.7
string.format ("%5s", "hi")          --&gt; '   hi'
string.format ("%-5s", "hi")         --&gt; 'hi   '
string.format ("%.4s", "Nick Gammon")--&gt; 'Nick'  (truncation)
string.format ("%9.4s", "John Smith")--&gt; '     John'
string.format ("%.f", 4.4)           --&gt; '4'  (precision of zero)
string.format ("%.f", 4.5)           --&gt; '5'  (rounding)
string.format ("%#.f", 4.4)          --&gt; '4.' (decimal place forced)
</code>


name: string.gmatch
prototype: it = string.gmatch (str, pattern)
summary: Iterate over a string
doc_name: lua_string
description:
Returns an iterator function for returning the next capture from a pattern over a string. If there is no capture, the whole match is produced.

See string.find for an explanation of regular expressions.

<code>
for w in string.gmatch ("nick takes a stroll", "%a+") do
  print (w)
end -- for

--&gt; 

nick
takes
a
stroll

</code>

For this function, a '^' at the start of a pattern does not work as an anchor, as this would prevent the iteration.


name: string.len
prototype: n = string.len (str)
summary: Return the length of a string
doc_name: lua_string
description:
Returns the length of the string, including any imbedded zero (0x00) bytes.

<code>
string.len ("hi there") --&gt; 8
</code>

You can also use #string to find its length.

<code>
#"hi there" --&gt; 8
</code>


name: string.gsub
prototype: s, n = string.gsub (str, pattern, replacement, n)
summary: Substitute strings inside another string
doc_name: lua_string
description:
Returns a copy of str with matches to 'pattern' replaced by 'replacement', for a maximum of n times.
As a second result it returns the number of matches made.

'replacement' can be a string in which case it simply replaces the matching pattern. However %1 through to %9 in the replacement pattern can refer to captured strings in the source pattern. %% becomes %. Also, %0 in the replacement pattern refers to the entire matching string.

If 'replacement' is a function it is called for each match with the matching string as an argument. It should return a string which is the string to replace it with. If it returns nil the original string is retained.

If 'replacement' is a table then the matching string is looked up in the table for each match, and if found, the replacement is substituted.

See <b>string.find</b> for an explanation of regular expressions.

<code>
string.gsub ("nick eats fish", "fish", "chips") --&gt; nick eats chips

-- example of using a function as the replacement

replacements = { 
   ["nice"] = "windy",
   ["walk"] = "stroll",
   }
   
s = "a nice long walk"

result = string.gsub (s, "%a+", 
  function (str)
  return replacements [str]
  end
  )

print (result) --&gt; a windy long stroll

-- An alternative way of doing a table replacement using the above table:

result = string.gsub (s, "%a+", replacements)

print (result) --&gt; a windy long stroll

-- You can call inbuilt functions too:

s = "a nice long walk"

result = string.gsub (s, "%f[%a]%a%a", string.upper)

print (result) --&gt; a NIce LOng WAlk

</code>

If you need to search for something that is <b>not</b> a regular expression, you need to "fix up" the search string first. This should do it:

<code>
search = string.gsub (search, "[%%%]%^%-$().[*+?]", "%%%1")
</code>

The code above fixes all of the special characters recognized in a regular expression by preceding them with a percent symbol.


name: string.match
prototype: cap1, cap2, cap3 = string.match (str, pattern, index)
summary: Searches a string for a pattern
doc_name: lua_string
description:
Find the first match of the regular expression "pattern" in "str", starting at position "index".

The starting position (index) is optional, and defaults to 1 (the start of the string).

If found, returns any captures in the pattern. If no captures were specified the entire matching string is returned.

If not found, returns nil.

This is similar to string.find, except that the starting and ending index are not returned.

<code>
print (string.match ("You see dogs and cats", "s..")) --&gt; see
</code>

See <b>string.find</b> for an explanation of regular expressions.

Note: string.match does not have the option for a "plain" search. If you want to do a search without regular expressions, use string.find.


name: string.reverse
prototype: s = string.reverse (str)
summary: Reverses the order of characters in a string
doc_name: lua_string
description:
Returns a string that is the string str reversed.

<code>
string.reverse ("nickgammon") --&gt; nommagkcin
</code>


name: string.sub
prototype: s = string.sub (str, start, end)
summary: Returns a substring of a string
doc_name: lua_string
description:
Returns a substring of the string, starting at index 'start' and ending at index 'end'. Both may be negative to indicate counting from the right. The end point is optional and defaults to -1, which is the entire rest of the string.

<code>
string.sub ("ABCDEF", 2, 3)  --&gt; BC
string.sub ("ABCDEF", 3)     --&gt; CDEF
string.sub ("ABCDEF", -1)    --&gt; F
</code>

See also utils.utf8sub for doing the identical operation with UTF-8 strings.


name: assert
prototype: v = assert (v, message)
summary: Asserts that condition is not nil and not false
doc_name: lua_base
description:
Raises an error if value of v is nil or false. 

Message is optional, defaults to "assertion failed!".

If no error, returns the value v.

<code>
assert (5 == 6, "oh no!") --&gt; error: oh no!
</code>

It is very useful that assert returns the value on success, as you can build an assert into the same line that does something that might fail. For example:

<code>
assert (loadstring ("print 'hello, world'")) ()
</code>

In this case if the loadstring function succeeds it returns a function, that is then executed by the final brackets, otherwise you get an error message.


name: collectgarbage
prototype: collectgarbage (opt, arg)
summary: Collects garbage
doc_name: lua_base
description:
Note that this has changed considerably since Lua 5.0.

<ul>
<li/>"stop": stops the garbage collector.
<li/>"restart": restarts the garbage collector.
<li/>"collect": performs a full garbage-collection cycle (this is the default if no option supplied)
<li/>"count": returns the total memory in use by Lua (in Kbytes).
<li/>"step": performs a garbage-collection step. The step "size" is controlled by arg (larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value of arg. Returns true if the step finished a collection cycle.
<li/>"setpause": sets arg/100 as the new value for the pause of the collector (see below).
<li/>"setstepmul": sets arg/100 as the new value for the step multiplier of the collector (see below).
</ul>

Lua implements an incremental mark-and-sweep collector. It uses two numbers to control its garbage-collection cycles: the garbage-collector pause and the garbage-collector step multiplier.

The garbage-collector pause controls how long the collector waits before starting a new cycle. Larger values make the collector less aggressive. Values smaller than 1 mean the collector will not wait to start a new cycle. A value of 2 means that the collector waits for the total memory in use to double before starting a new cycle.

The step multiplier controls the relative speed of the collector relative to memory allocation. Larger values make the collector more aggressive but also increase the size of each incremental step. Values smaller than 1 make the collector too slow and may result in the collector never finishing a cycle. The default, 2, means that the collector runs at "twice" the speed of memory allocation.

Both "setpause" and "setstepmul" get percentage points as arguments (so an argument of 100 means a real value of 1). Both default to 200 when Lua starts up (and since they are divided by 100, effectively the default is 2 as described above).

<code>
collectgarbage ("collect") --&gt; forces garbage collection
</code>


name: dofile
prototype: val = dofile (filename)
summary: Executes a Lua file
doc_name: lua_base
description:
Opens the named file, parses and executes its contents as a Lua chunk. 
Raises errors if they occur. Returns any value returned by the chunk.

For example:

<code>
dofile ("myfile.lua") 
</code>

Using dofile is the same as:

<code>
function dofile (filename)
  local f = assert (loadfile (filename))
  return f ()
end -- dofile
</code>


name: error
prototype: error (message, level)
summary: Raises an error message
doc_name: lua_base
description:
Raises an error with the supplied message. Never returns. If a level is supplied the error points to the current function (level 1 or nil), the parent function (level 2) and so on.

<code>
error ("Insufficient funds") --&gt; error raised: "Insufficient funds"
</code>

If you are writing a "validation function" that checks things passed to it, you would normally make the level 2, so that the error message points to the line that calls the validator, rather than the validator itself.


name: gcinfo
prototype: k = gcinfo ()
summary: Returns amount of dynamic memory in use
doc_name: lua_base
description:
Returns Kb of dynamic memory in use.

This function is deprecated in Lua 5.1. Use collectgarbage ("count") instead.

<code>
print (gcinfo ()) --&gt; 103
</code>


name: getfenv
prototype: t = getfenv (f)
summary: Returns the current environment table
doc_name: lua_base
description:
Returns the current environment used by the nominated function f. 
f can be a function or a number representing the stack level, where 1 is the currently running function, 2 is its parent and so on.

The environment is where "global" variables are stored.

<code>
print (getfenv (1)) --&gt; table: 02072780
print (_G) --&gt; table: 02072780
</code>

The default for f is 1 (the current function).


name: getmetatable
prototype: t = getmetatable (obj)
summary: Returns the metatable for the object
doc_name: lua_base
description:
Returns metatable for the nominated object, which can be:

<ul>
<li/>nil if no metatable
<li/>the value of the __metatable field of the metatable, if any
<li/>the metatable of the object
</ul>

<code>
getmetatable (_G) --&gt; nil
</code>

In Lua 5.1, all objects can have metatables (not just tables).


name: ipairs
prototype: it, t, 0 = ipairs (t)
summary: Iterates over a numerically keyed table
doc_name: lua_base
description:
Returns an iterator function, the table t, and 0, for use in the generic "for" loop.


<code>
for i, v in ipairs (t) do
  -- process loop here (i is the key, v is the value)
end -- for
</code>

The iterator function, called repeatedly, returns the key and value pairs for each table item, starting at 1, until it finds the first missing integer key. For example, if keys 1 to 8 are present, and key 9 is nil, it will return the first 8 values. This occurs even if key 10 is present.

In other words, you cannot use ipairs to iterate over a table with "holes" in the key ranges.

If the table has non-numeric keys, there are gaps in the key sequence, or keys do not start at 1, then you need to use pairs (instead of ipairs) to access every item in the table (however this access will not necessarily be in numeric sequence).

Most usually you simply use ipairs to traverse a numerically-keyed table, for example:

<code>
t = {
    "the",
    "quick",
    "brown",
    "dog",
   }

for key, value in ipairs (t) do
  print (key, value)
end -- for
</code>

Example output:

<code>
1 the
2 quick
3 brown
4 dog
</code>

In this case the keys (automatically assigned) were 1, 2, 3, 4, and the values were the words in the table.


name: load
prototype: f = load (loader, debugname)
summary: Loads a chunk by calling a function repeatedly
doc_name: lua_base
description:
Loads a chunk using function <b>loader</b> to get its pieces. Each call to <b>loader</b> must return a string that concatenates with previous results. A return of nil (or no value) signals the end of the chunk.

If there are no errors, returns the compiled chunk as a function; otherwise, returns nil plus the error message. The environment of the returned function is the global environment. 

This could be used to gradually build up a chunk (for example from a network), or to write a preprocessor that reads in a file, preprocess it (like the C preprocessor) and returns the altered code to the Lua interpreter.

The example below shows generating code from entries in a table.

<code>
function getcode (t)
local pos = 0
  local function iterator (s)
    pos = pos + 1
    return t [pos]
  end -- iterator
  return iterator
end -- getcode


code = {
  "local a = 1 ",
  "print ('a =', a) ",
  "print 'done.'"
  }
  
assert (load (getcode (code))) ()
</code>


name: loadfile
prototype: f, err = loadfile (filename)
summary: Loads a Lua file and parses it
doc_name: lua_base
description:
Opens the named file, parses it and returns the compiled chunk as a function. Does not execute it.

<code>
f = assert (loadfile ("myfile.lua"))
f () -- execute function now
</code>

Compare to dofile, which executes it as well. That is, dofile is equivalent to the two lines of code above.

If there is an error in the loading process, for example the file is not found, or it is found but has a syntax error, then f will be nil and err will be the nature of the error.


name: loadstring
prototype: f = loadstring (str, debugname)
summary: Compiles a string of Lua code
doc_name: lua_base
description:
Parses the string and returns the compiled chunk as a function. Does not execute it.

If the string cannot be parsed returns nil plus an error message.

The optional debugname is used in debug error messages.

<code>
f = assert (loadstring ("print 'hello, world'"))
f ()   --&gt; hello, world
</code>

You can avoid the intermediate variable "f" in this example by simply putting the brackets on the same line:

<code>
assert (loadstring ("print 'hello, world'")) () --&gt; hello, world
</code>

If the string was produced by string.dump, loadstring converts it back into the original function.

<code>
function f () print "hello, world" end
s = string.dump (f)
assert (loadstring (s)) () --&gt; hello, world
</code>


name: module
prototype: module (name, ···)
summary: Creates a Lua module
doc_name: lua_base
description:
Creates a module. This is intended for use with external "package" files, however it can be used internally as shown in the example below. The module effectively has its own global variable space (because module does a setfenv) so that any functions or variables used in the module are local to the module name (for example, foo.add in the example below).

If there is a table in package.loaded[name], this table is the module. Thus, if the module has already been requested (by a require statement) another new table is not created.

Otherwise, if there is a global table t with the given name, this table is the module. 

Otherwise creates a new table t and sets it as the value of the global name and the value of package.loaded[name].

This function also initializes t._NAME with the given name, t._M with the module (t itself), and t._PACKAGE with the package name (the full module name minus last component). 

Finally, module sets t as the new environment of the current function and the new value of package.loaded[name], so that require returns t.

The example below shows the creation of the module "foo". In practice you would probably put the contents of the "test" function into a separate file, and then: require "test"

The nice thing about this approach is that nothing inside the module will "pollute" the global namespace, excepting the module name itself (foo in this case). Internally inside the module functions can call each other without having to use the package name (eg. add could call subtract without using foo.subtract).

You can make a "private" function inside the "foo" package by simply putting "local" in front of the function name.

<code>
function test ()
  local print = print  --&gt; we need access to this global variable
  
  module "foo"  --&gt; create the module now
  
  function add (a, b)
    return a + b
  end -- add
  
  function subtract (a, b)
    return a - b
  end -- subtract

  function hello (s)
    print ("hello", s)
  end -- hello

end -- function test

test ()  -- install module

foo.hello ("world")   --&gt; hello	world
print (foo.add (2, 3))  --&gt; 5
print (foo.subtract (7, 8))  --&gt; -1

print (package.loaded["foo"]) --&gt; table: 003055F0
print (foo)  --&gt; table: 003055F0

for k, v in pairs (foo) do
  print (k, v)
end -- for 

--&gt;

_M	table: 003055F0
_NAME	foo
_PACKAGE	

hello	function: 00305810
subtract	function: 00305760
add	function: 00305780
</code>

After the module has been created, we can see that:

foo._M is foo itself (ie. the module)
foo._NAME is "foo"
foo._PACKAGE is an empty string (if the module was "foo.bar" then _PACKAGE would be "foo.")


name: next
prototype: index, value = next (table, index)
summary: Returns next key / value pair in a table
doc_name: lua_base
description:
Traverses all entries in a table. Returns the next index, value pair. If index is nil (the default), returns the first pair. When called with the last index of the table (or with an index of nil for an empty table), returns nil.

Only non-nil values are returned. Order is not specified (eg. is not necessarily alphabetic sequence). Behaviour is undefined if you assign values to non-existent fields during the traversal. You may however modify or delete existing fields.

<code>
t = { "hello", "world" }

for k, v in next, t do
  print (k, v)
end 

--&gt;

1 hello
2 world
</code>

See also the pairs function, which uses next. The above code could be written as:

<code>
for k, v in pairs (t) do
  print (k, v)
end 
</code>

If you want to know if a table is empty, or not, you can test:

<code>
if next (t) == nil then
  -- table t is empty
end -- if empty
</code>


name: pairs
prototype: next, t, nil = pairs (t)
summary: Traverse all items in a table
doc_name: lua_base
description:
Returns the 'next' function, the table t, and nil, for use in a for loop.

<code>
t = { "hello", "world" }

for k, v in pairs (t) do
  print (k, v)   -- k is the key, v is the value
end 
</code>

Compare to ipairs which only traverses numerically-keyed entries.

Use the pairs function to traverse any table. The table will not necessarily be accessed in alphabetic (or any particular) order.

You must <b>not</b> add additional entries to the table during traversal. Doing so is undefined (that is, the script may crash or loop).

You are permitted to delete items from the table during traversal. In other words, if you find an item you want to delete you may assign nil to it, to delete it.


name: pcall
prototype: ok, result [ , result2 ...] = pcall (f, arg1, arg2, ...)
summary: Calls a function in protected mode
doc_name: lua_base
description:
Calls function f with the supplied arguments in protected mode. Catches errors and returns:

On success:

<ul>
<li/>true
<li/>function result(s) - may be more than one
</ul>

On failure:

<ul>
<li/>false
<li/>error message
</ul>


<code>
function f (v)
  return v + 2
end -- f

a, b = pcall (f, 1)
print (a, b) --&gt; true 3

a, b = pcall (f, "a")
print (a, b)  --&gt; false   stdin:2: attempt to perform arithmetic on local `v' (a string value)

</code>


name: print
prototype: print (a1, a2, a3, ...)
summary: Prints its arguments
doc_name: lua_base
description:
Prints its arguments to stdout (or the output window in the case of MUSHclient, using world.Note), formatted by calling 'tostring'. Not intended for formatted output, but rather for debugging. Each argument is separated by a space.

<code>
print ("Hello", "world", 123, assert) --&gt; Hello world 123 function: 02071C00
</code>

For formatted output, see string.format.


name: rawequal
prototype: b = rawequal (v1, v2)
summary: Compares two values for equality without invoking metamethods
doc_name: lua_base
description:
Returns a boolean depending on v1 == v2 without invoking any table metamethods.

<code>
print (rawequal (3, 3))) --&gt; true
</code>


name: rawget
prototype: v = rawget (table, index)
summary: Gets the value of a table item without invoking metamethods
doc_name: lua_base
description:
Gets the real value of table [index] without invoking metamethods. Index should not be nil.

<code>
print (rawget (_G, "Note")) --&gt; nil
print (rawget (world, "Note"))  --&gt; function: 02058190
print (Note) --&gt; function: 02058190 
</code>

This example shows that the Note function is not really in the global environment. MUSHclient adds a metamethod to pull it from the "world" table.


name: rawset
prototype: rawset (table, index, value)
summary: Sets the value of a table item without invoking metamethods
doc_name: lua_base
description:
Sets the value of table [index] to value, without invoking metamethods. 'table' must be a table, and 'index' must not be nil.

<code>
rawset (_G, "test", 42) 
print (test) --&gt; 42
</code>


name: require
prototype: val = require (modname)
summary: Loads a module
doc_name: lua_base
description:
Loads the named module. 

First checks the table package.loaded to see if it has already been loaded. If so, returns the value there.

Otherwise it tries to find a loader for the module. It tries these things:

<ul>
<li/>If the table item package.preload [modname] is a function, that is called as the module loader.

<li/>Process the variable package.path, substituting modname where it has a "?" (that is, ? becomes the name) and then repeatedly attempting to open the files in the list (paths separated by semicolons) as Lua source files. The first attempt in the default configuration is in the current directory, for modname.lua, then in the executable directory (that is, where MUSHclient executable is, if you are running from MUSHclient), various combinations of subdirectories and file names. To see exactly what tests are being done, just type 'require "foo"' and the error message will show you.

<li/>Process the variable package.cpath, substituting modname where it has a "?" (that is, ? becomes the name) and then repeatedly attempting to open the files in the list (paths separated by semicolons) as DLLs. This attempts to load various DLLs, again see the package.cpath variable to see which ones exactly, or try a dummy require, as described above. If a DLL is found it attempts to call the function "luaopen_" concatenated with the module name, where dots are replaced by underscores.

<li/>Finally if all else fails try to load the all-in-one loader (executable-path/loadall.dll) and look for an appropriate function.
</ul>

Once a loader is found, require calls the loader with a single argument, modname. If the loader returns any value, require assigns the returned value to package.loaded [modname]. If the loader returns no value and has not assigned any value to package.loaded [modname], then require assigns true to this entry. In any case, require returns the final value of package.loaded [modname].

<code>
f = require ("test")  --&gt; loads module "test" 
</code>

Effectively this lets various modules "require" a package, and it will only be loaded once. Also see the description for "module" for ways of effectively setting up a module to work in conjunction with "require".


name: select
prototype: items = select (index, ...)
summary: Returns items in a list
doc_name: lua_base
description:
If index is a number, returns <b>all</b> items in the list from that number onwards. Otherwise index must be the string "#", in which case it returns the number of items in the list. This can be used to simulate the behaviour of the old "arg" feature in Lua 5.0, for use with variable numbers of arguments passed to a function.

<code>
function f (...)
  print (select ("#", ...))  --&gt; 4
  print (select (2, ...))    --&gt; 20  30  40
end -- f

f (10, 20, 30, 40)
</code>


name: setfenv
prototype: f = setfenv (f, env)
summary: Sets a function's environment
doc_name: lua_base
description:
Sets the current environment to be used by f, which can be a function, userdata, thread or stack level. Level 1 is the current function. Level 0 is the global environment of the current thread. The "env" argument is a table, which effectively becomes the "root" for the environment.

The return value is the function whose environment was changed, unless the argument was 0.

<code>
function f (v)
  test = v  -- assign to global variable test
end -- function f

local myenv = {}  -- my local environment table
setfenv (f, myenv)  -- change environment for function f
f (42)  -- call f with new environment

print (test) --&gt; nil  (global test was not changed)
print (myenv.test)  --&gt; 42  (test inside myenv was changed)
</code>

This can be used as a form of "sandbox", so that functions can run in an environment where they do not have access to normal global variables. For example, in the above code, you could not call "print" from inside function f, as print is not in the environment. To make it accessible you might do this:

<code>
myenv.print = print -- copy print function into environment table
</code>

A nice use of the setfenv function is to limit the damage that can be done when reading an external file.
An example is to let the user of your script provide a configuration file, that you want to read in. An example might be:

<code>
a = 42
b = "nick"
c = { "the", "quick", "brown", "fox" }
</code>

A quick way of processing that file would be to: dofile ("config.txt")
However if the "config.txt" file contained malicious code (like: os.remove "myapplication.exe") then it could have undesired side-effects. Even a simple assignment like: 'print = nil' could cause problems. The solution is to use setfenv to limit the global environment for this file, like this:

<code>
config = {} -- empty environment table
-- load the file, get a function to execute  
local f = assert (loadfile ("config.txt"))
-- want to load file into the config table
setfenv (f, config)
-- load it
f ()
print (config.a)  --&gt; 42 
</code>

What this does is change the global environment for the function returned from loadfile to be the empty config table. This means that all "global" variables will be relative to config, not _G. It also means that all the standard functions (like os.remove) are not visible.


name: setmetatable
prototype: t = setmetatable (t, metatable)
summary: Sets the metatable for a table
doc_name: lua_base
description:
Sets the metatable for the nominated table. If metatable is nil, removes the metatable. If the original metatable has a "__metatable" entry an error is raised.

Returns the table.

Metatables let you add special entries that cause certain operations to behave in a different way. These operations are (each one starts with 2 underscore characters):

<ul>
<li/>__add - the + operation
<li/>__sub - the - operation
<li/>__mul - the * operation
<li/>__div - the / operation
<li/>__pow - the ^ (exponentiation) operation
<li/>__unm - the unary minus operation

<li/>__concat - the .. (concatenate) operation

<li/>__eq - the == operation (a ~= b is the same as not (a == b))
<li/>__lt - the &lt; operation (a &gt; b is the same as b &lt; a)
<li/>__le - the &lt;= operation (a &gt;= b is the same as b &lt;= a)

<li/>__index - called if an antry is not in the table - prototype is: function f  (table, key) 
<li/>__newindex - called when adding an entry to the table - prototype is: function f (table, key, value)
<li/>__call - called if you attempt to "call" the table
<li/>__gc - called after garbage collection (userdata only)
<li/>__mode - if it contains "k", keys are weak, if it contains "v", values are weak
<li/>__metatable - if present metatable cannot be changed, and this is the error message
<li/>__tostring - called to convert the argument to a string
<li/>__len - the length operator (#)

</ul>

If there is no __le metamethod, Lua tries the __lt metamethod, assuming that:

<code>
a &lt;= b  is equivalent to:  not (b &lt; a)
</code>

Examples:

<code>
-- define adding to the table
t = { age = 42, height = 102 }
m = { __add = function (tbl, n) return t.age + n end }
setmetatable (t, m)
print (t + 1)  --&gt; 43

-- define calling the table
t = { age = 42, height = 102 }
m = { __call = function (t) table.foreach (t, print) end }
setmetatable (t, m)
t ()  -- "call" the table (this prints each entry)

--&gt;

height 102
age 42
</code>


name: tonumber
prototype: n = tonumber (n, base)
summary: Converts a string (of the given base) to a number
doc_name: lua_base
description:
Converts n to a number using the optional base (default 10). Base can be from 2 to 36. For bases > 10 the letters a-z (not case sensitive) represent the digits. (eg. F is 15).
For decimal numbers you can supply fractions and exponents. Others should be unsigned.
Returns nil if the number cannot be converted.

<code>
print (tonumber ("100100", 2)) --&gt; 36
print (tonumber ("1e5")) --&gt; 100000
print (tonumber ("1EF", 16)) --&gt; 495 
</code>

You can use tonumber as a quick check if a variable contains something convertable to a number. 

<code>
print (tonumber ("abc")) --&gt; nil
print (tonumber ("-43")) --&gt; -43
print (tonumber (-43))   --&gt; -43
</code>

To see if the variable actually is already a number type, use the "type" function:

<code>
print (type ("-43")) --&gt; string
print (type (-43))   --&gt; number
</code>

See also bit.tonumber which will handle larger numbers.


name: tostring
prototype: s = tostring (a)
summary: Converts its argument to a string
doc_name: lua_base
description:
Converts its argument to a string in a reasonable format. If a __tostring metatable field is found, that is used for the conversion.

<code>
print (tostring (print)) --&gt; function: 0205A980
print (tostring (_G)) --&gt; table: 02072780
print (tostring (1.23e10)) --&gt; 12300000000

-- use __tostring to print a table

t = { age = 42, height = 102 }

setmetatable (t, 
  { 
  __tostring = function (t) 
    return "person of age " .. t.age
    end -- __tostring 
  }
 )

print (t) --&gt; person of age 42

</code>

Also see bit.tostring which will convert a number to a string of any base in the range 2 to 36.


name: type
prototype: s = type (v)
summary: Returns the type of a variable
doc_name: lua_base
description:
Returns a string, which is the type of the supplied variable:

<ul>
<li/>nil
<li/>number
<li/>string
<li/>boolean
<li/>table
<li/>function
<li/>thread
<li/>userdata
</ul>

<code>
print (type (42)) --&gt; number
print (type ("42")) --&gt; string
print (type (string)) --&gt; table
print (type (tonumber)) --&gt; function
</code>

Note that if its argument is nil, it returns "nil" - that is the string containing the word "nil".


name: unpack
prototype: t1, t2, ... = unpack (t)
summary: Unpacks a table into individual items
doc_name: lua_base
description:
Returns all elements from the given list (table) as individual values. This is equivalent to:

return t [1], t [2], t [3] ..., t [n]

<code>
t = { "the", "quick", "brown" }

print (unpack (t)) --&gt; the quick brown
</code>

An example of using unpack is the case of a variable number of arguments to a function, where you want to pass those to another function.

For example, to make an error function that takes a formatted string:

<code>
function ferror (fmt, ...)
  error (string.format (fmt, unpack (arg)), 2)
end -- ferror
</code>

However in Lua 5.1 this is more simply written as:

<code>
function ferror (fmt, ...)
  error (string.format (fmt, ...), 2)
end -- ferror
</code>


name: xpcall
prototype: ok, result = xpcall (f, err)
summary: Calls a function with a custom error handler
doc_name: lua_base
description:
Calls function f with err as the custom error handler. 

If an error occurs in f it is caught and the error-handler 'err' is called. Then xpcall returns false, and whatever the error handler returned.

If there is no error in f, then xpcall returns true, followed by the function results from f.
 
Note that the supplied error function is called before the stack is unwound (in case of error) so this is a good time to find what functions were on the stack leading up to the error. In the example below we use the debug.traceback function, which shows a stack trace as at the time of the error.

<code>
function f ()
  return "a" + 2  -- will cause error
end -- f

function err (x)
  print ("err called", x)
  return "oh no!"
end -- err

print (xpcall (f, err))

 --&gt;
 
err called [string "Immediate"]:2: attempt to perform arithmetic on a string value
false oh no!

function f2 ()
  return 2 + 2
end -- f

print (xpcall (f, err))  --&gt; true 4

function f ()
return "a" + 2
end -- f

print (xpcall (f, debug.traceback))

 --&gt;

false   stdin:2: attempt to perform arithmetic on a string value
stack traceback:
        stdin:2: in function `f'
        [C]: in function `xpcall'
        stdin:1: in main chunk
        [C]: ?

</code>


name: bit.shr
prototype: n = bit.shr (num, bits)
summary: Shifts a number right
doc_name: lua_bit
description:
This takes two arguments. Both are converted to unsigned 'long long' (64-bit unsigned integers). The first argument is shifted right the number of bits in the second argument.

eg.

<code>
print (bit.shr (1024, 6)) --&gt; 16
</code>


name: bit.shl
prototype: n = bit.shl (num, bits)
summary: Shifts a number left
doc_name: lua_bit
description:
This takes two arguments. The first is converted to signed 'long long' (64-bit integer), the second to unsigned 'long long' (64-bit unsigned integer). The first argument is shifted left the number of bits in the second argument.

You can use this for signed or unsigned numbers, as the sign bit will still be preserved.

eg.

<code>
print (bit.shl (4, 6)) --&gt; 256
</code>


name: bit.ashr
prototype: n = bit.ashr (num, bits)
summary: Shifts a number right, preserving sign
doc_name: lua_bit
description:
This takes two arguments. The first is converted to signed 'long long' (64-bit integer), the second to unsigned 'long long' (64-bit unsigned integer). The first argument is shifted right the number of bits in the second argument.

Use this version for shifting signed numbers right, as it preserves the sign. (The other version, bit.shr, will shift the sign bit into the number part).

eg.

<code>
print (bit.ashr (-1024, 6)) --&gt; -16
</code>


name: bit.band
prototype: n = bit.band (a, b, ...)
summary: Bitwise 'and'
doc_name: lua_bit
description:
This takes one or more arguments. All are converted to signed 'long long' (64-bit integers). The result is all arguments "and-ed" together bitwise.
eg.

<code>
print (bit.band (15, 7, 3)) --&gt; 3
</code>


name: bit.bor
prototype: n = bit.bor (a, b, ...)
summary: Bitwise 'or'
doc_name: lua_bit
description:
This takes one or more arguments. All are converted to signed 'long long' (64-bit integers).  The result is all arguments "or-ed" together bitwise.
eg.

<code>
print (bit.bor (1, 2, 8)) --&gt; 11
</code>

Effectively this sets bits (eg. flags).

Note that clearing a bit can be done with bit.clear.


name: bit.xor
prototype: n = bit.xor (a, b, ...)
summary: Bitwise 'exclusive or'
doc_name: lua_bit
description:
This takes one or more arguments. All are converted to signed 'long long' (64-bit integers). The result is all arguments "exclusive or-ed" together bitwise.
eg.

<code>
print (bit.xor (15, 1)) --&gt; 14
</code>


name: bit.neg
prototype: n = bit.neg (a)
summary: Bitwise 'negate' (ones complement)
doc_name: lua_bit
description:
This takes one argument. It is converted to a signed 'long long' (64-bit integer). The result is the ones-complement of the number (zero bits become one, one bits become zero).
eg.

<code>
print (bit.neg (1)) --&gt; -2
print (bit.band (14, bit.neg (8)))  --&gt; 6  (clear 8-bit)
</code>

Also see bit.clear to achieve the same affect (clearing a bit).


name: bit.mod
prototype: n = bit.mod (a, b)
summary: Bitwise 'modulus' (remainder after integer divide)
doc_name: lua_bit
description:
This takes two arguments. Both are converted to signed 'long long' (64-bit integers). The result is modulus - the remainder after doing an integer divide of the first argument by the second argument.
eg.

<code>
print (bit.mod (17, 4))  --&gt; 1
</code>


name: bit.tonumber
prototype: n = bit.tonumber (s, base)
summary: Convert a string into a number
doc_name: lua_bit
description:
This takes a string, and converts it into a number. Unlike the standard Lua tonumber function this function will handle up to a 52-bit number (the default Lua number conversion will only go to 32-bit numbers).

eg.

<code>
print (bit.tonumber ("A7C5AC471", 16)) --&gt;  45035996273
</code>

The base is optional and defaults to 10. The base can be in the range 2 to 36. Fractional numbers are not supported, nor are numbers with exponents (eg. 10.24e15). For such numbers use the standard Lua "tonumber" function.

Because of limitations in the size of a floating point number, the maximum string value that can be converted is a 52 bit number, ie: hex FFFFFFFFFFFFF (decimal 4503599627370495).

Leading whitespace is skipped. After that, there can be an optional + or - sign.


name: bit.tostring
prototype: s = bit.tostring (n, base)
summary: Convert a number into a string
doc_name: lua_bit
description:
This takes a number, and converts it into a string to the given base, in uppercase. The base is optional and defaults to 10. The base can be in the range 2 to 36. Fractional parts are discarded, as the number is first converted to a 64-bit number internally. Negative numbers are OK, and will be converted with a leading "-" sign.

eg.

<code>
print (bit.tostring (45035996273, 16)) --&gt;  A7C5AC471
</code>


name: utils.compress
prototype: s = utils.compress (s [, method] )
summary: Compress a string
doc_name: lua_utils
description:
Compresses string s and returns the compressed form. Note that it may contain nulls (bytes with a zero value).

The optional argument 'method' indicates the level of compression you want.

<ul>
<li/>0 = no compression
<li/>1 = best speed
....
<li/>9 = best compression
</ul>

The default, if omitted, is 6.

eg.

<code>
comp = utils.compress ("this is a fine thing")
</code>

For short strings the compressed data may be longer than the uncompressed data because of a 12-byte "compression information" header that is prepended to the compressed data. For longer text (such as the section above about the Lua sandbox), the compression ratio is about 50%.


name: utils.decompress
prototype: s = utils.decompress (s)
summary: Decompress a string
doc_name: lua_utils
description:
Decompresses string s and returns the decompressed form. Raises an error if decompression cannot be done (eg. bad compressed data).

The two functions utils.compress and utils.decompress should be complementary, so that this should always be true:

<code>
x = "some string" -- for any (string) data whatsoever 
y = utils.decompress (utils.compress (x)) --&gt; y should be same as x
</code>


name: utils.hash
prototype: s = utils.hash (s)
summary: Hash a string, returning the hex codes
doc_name: lua_utils
description:
Returns a 40-character hex string which is the hash of the string 's'. The string 's' may contain the null byte (ie. hex 00). Otherwise, this is the same behaviour as the world.Hash function.

eg.

<code>
print (utils.hash ("Nick Gammon")) --&gt; fe09b07227a4e006213ac005831d55b20508a568
print (Hash ("Nick Gammon")) --&gt; fe09b07227a4e006213ac005831d55b20508a568
</code>


name: utils.sha256
prototype: s = utils.sha256 (s)
summary: Hash a string using a 256-bit hash
doc_name: lua_utils
description:
This returns a 256-bit SHA hash (Secure Hash Algorithm) of the string s, which may contain binary zeroes. Unlike the utils.hash function this returns the result as a straight 32-byte (256-bit) field (that is, not converted to printable hex). If you want it in readable form you must then convert it yourself (eg. with utils.tohex).

eg.

<code>
print (utils.tohex (utils.sha256 ("nick gammon")))
--&gt; result: B3223193E1C89CB1E42E2BE2DF34874320F43E149DC315A381B08B7BC52849AD
</code>

This is a more secure hash than the standard utils.hash algorithm, which returns a 160-bit hash.


name: utils.md5
prototype: s = utils.md5 (s)
summary: Hash a string using the 128-bit MD5 algorithm
doc_name: lua_utils
description:
This returns a 128-bit MD5 hash of the string s, which may contain binary zeroes. Unlike the utils.hash function this returns the result as a straight 16-byte (128-bit) field (that is, not converted to printable hex). If you want it in readable form you must then convert it yourself (eg. with utils.tohex).

eg.

<code>
print (utils.tohex (utils.md5 ("nick gammon")))
--&gt; result: 9A380FD967D936AC99ED73B4A038CE8C
</code>


You can write a small Lua program to do the same thing that the md5sum program does (in Linux, Cygwin etc.):

<code>
f = io.open ("docs/RegularExpressions.txt", "rb")
if f then
  print (utils.tohex (utils.md5 (f:read ("*a"))))
  f:close () 
end -- if

--&gt; result: 3764E22E2AC5BA67997C42C288253101
</code>

Compare this to the output from md5sum using Cygwin:

<code>
$ md5sum RegularExpressions.txt
3764e22e2ac5ba67997c42c288253101 *RegularExpressions.txt
</code>

The hash is the same, apart from not being in lower case, which you can change with the string.lower function if you want.


name: utils.base64encode
prototype: s = utils.base64encode (s [, linebreaks])
summary: Encode a string with base-64 encoding
doc_name: lua_utils
description:
Encodes the string 's' in base64 encoding (suitable for emails etc.). If 'linebreaks' is true, there will be a carriage return/linefeed every 76 characters. The string 's' may contain the null byte (ie. hex 00). Otherwise, this is the same behaviour as the world.Base64Encode function.

eg.

<code>
print (utils.base64encode ("Nick Gammon")) --&gt; TmljayBHYW1tb24=
</code>

The output string will be 4/3 times as large as the input string, plus some possible padding to make up the result to a multiple of 4 (the padding character is "="). Also, if you request linebreaks there will be a further 2 byte for every 76 bytes output (that is, every 57 bytes of input). The default is to not have linebreaks.


name: utils.base64decode
prototype: s = utils.base64decode (s)
summary: Decode a string which was base-64 encoded
doc_name: lua_utils
description:
Decodes the string 's' from base64 encoding to plain text. The decoded string may contain the null byte (ie. hex 00). Otherwise, this is the same behaviour as the world.Base64Decode function. Bytes that are invalid are skipped (eg. spaces, newlines, other junk).

eg.

<code>
print (utils.base64decode ("TmljayBHYW1tb24=")) --&gt; Nick Gammon
</code>

If the source string is not a multiple of 4 bytes then the last few bytes of the decoded string will be lost (because decoding is done in batches of 4 input bytes to 3 output bytes).


name: utils.tohex
prototype: s = utils.tohex (s)
summary: Convert a string into hex
doc_name: lua_utils
description:
This converts the string s to hexadecimal (printable) form. The string may contain binary zeroes. Use string.lower to make a lower-case version if that is what you prefer.

eg.

<code>
print (utils.tohex ("Nick Gammon")) --&gt; 4E69636B2047616D6D6F6E
</code>


name: utils.fromhex
prototype: s = utils.fromhex (s)
summary: Convert a string from hex
doc_name: lua_utils
description:
This converts the supplied hexadecimal string s back to a normal string. The converted string may contain binary zeroes. 

eg.

<code>
print (utils.fromhex ("4E69636B2047616D6D6F6E")) --&gt; Nick Gammon
</code>

The supplied string may contain 'space' characters (0x09 – 0x0D or 0x20) which are ignored, otherwise if it contains characters other than A-F, a-f or 0-9 this function raises an error. If the number of characters is odd then the last character is treated as the low-order nibble of the final byte. eg.

<code>
a = utils.fromhex ("ABC") --&gt; same as utils.fromhex ("AB0C")
</code>

Note that "spaces are ignored" means that a sequence like "A B C D" is treated as the same as "ABCD" not "0A 0B 0C 0D".


name: utils.readdir
prototype: t = utils.readdir (s)
summary: Read a disk directory into a table
doc_name: lua_utils
description:
You can use utils.readdir to read an entire directory on your PC into a Lua table, based on the wildcard you supply.


For example:

<code>
t, e = utils.readdir ("c:/mushclient/plugins/*.xml")

assert (t, e) -- raises error on failure
</code>


If the directory specification is matched, the result from the call is a table of directory items, keyed by the filename. If the directory specification cannot be matched, or is invalid, it returns nil followed by an error message. You can simply test for non-nil, or call "assert" to report the error.

For each file in the directory (that matches the wildcard) the following is returned:

<ul>
<li/>size - file size in bytes
<li/>create_time - creation time (except for FAT filesystems, where it is omitted)
<li/>access_time - last access time (except for FAT filesystems, where it is omitted)
<li/>write_time - time written 
<li/>archive - true if archive. Set whenever the file is changed, and cleared by the BACKUP command.
<li/>hidden - hidden file. Not normally seen with the DIR command
<li/>normal - normal file. File can be read or written to without restriction. 
<li/>readonly - read-only. File cannot be opened for writing, and a file with the same name cannot be created. 
<li/>directory - Subdirectory. 
<li/>system - system file. Not normally seen with the DIR command.
</ul>

By detecting suddirectories you could conceivably recurse and find the contents of subdirectories as well.


name: utils.split
prototype: t = utils.split (s, delim)
summary: Split a delimited string into a table
doc_name: lua_utils
description:
The function utils.split is intended to do the reverse of table.concat. That is, it takes a string and generates a table of entries, delimited by single-character delimiters (such as comma or newline).

Example:

<code>
test = "the,quick,brown,dog,jumped"  
t = utils.split (test, ",")
tprint (t)
print (table.concat (t, ","))
</code>

Output:

<code>
1="the"
2="quick"
3="brown"
4="dog"
5="jumped"
the,quick,brown,dog,jumped
</code>

You pass utils.split 2 or 3 arguments:

<ul>
<li/>The string to be split
<li/>The single-character delimiter
<li/>(optional) the maximum number of splits to do
</ul>

If the 3rd argument is not supplied, or is zero, then the entire string is split. Otherwise, it will be split the number of times you specify. eg.

<code>
t = utils.split (test, ",", 2)
tprint (t)
</code>

Output:

<code>
1="the"
2="quick"
3="brown,dog,jumped"
</code>

In this case the remaining text is placed in the 3rd table item.


name: utils.xmlread
prototype: t = utils.xmlread (s)
summary: Parses an XML string into a nested table
doc_name: lua_utils
description:
The function utils.xmlread uses MUSHclient's internal XML parser to parse an XML string you supply. This effectively would let you parse triggers, aliases etc. that you have copied to the clipboard as text (or created with ExportXML script routine), and see exactly what each value is set to. Or, by reading a MUSHclient world file into memory as a string, you could parse that.

The XML parser is not necessarily 100% industry-standard XML parsing, however it is the method MUSHclient uses for its own XML documents, and should be reasonably compatible with standard XML unless you use some of the more fancy XML extensions. It should certainly parse the XML output by MUSHclient itself (eg. triggers, aliases, world files, plugins) as that is the same routine it uses to read them in.

You pass to the parser a single string, which is the XML to be parsed. If the parsing is successful three results are returned:

<ul>
<li/>The root node (all other nodes are children of this node)
<li/>The root document name (eg. "muclient")
<li/>A table of custom entities in the document, or nil if no custom entities
</ul>

If the parsing fails, three results are returned:

<ul>
<li/>nil - to indicate failure
<li/>The error reason
<li/>The line the error occurred at
</ul>

You can pass the first 2 results to "assert" to quickly check if the parsing was successful.

Each node consists of a table with the following entries:

<ul>
<li/>name - name of the node (eg. &lt;trigger&gt;foo&lt;/trigger&gt; - the name is "trigger") 
<li/>content - contents of the node (eg. &lt;trigger&gt;foo&lt;/trigger&gt; - the content is "foo")
<li/>empty - boolean to indicate if the node is empty. (eg. &lt;br/&gt; is an empty node)
<li/>line - which line in the XML string the node occurred on (eg. line 5)
<li/>attributes - a table of attributes for this node, keyed by the attribute name (eg. "world_file_version"="15"). 

Attribute names have to be unique so we can used a keyed lookup to find them.

The attributes table is not present if there are no attributes defined.

<li/>nodes - a table of child nodes, keyed by ascending number (the order they appeared in). Each child node has the same contents as described above.

Children are not necessarily unique (eg. there may be more than one &lt;trigger&gt; node in a document) so they are keyed by number, and not by node name.

The nodes table is not present if there are no children of this node.

</ul>

Example:

<code>
a, b, c = utils.xmlread ("&lt;foo&gt;&lt;bar x='2'/&gt;&lt;/foo&gt;")
require "tprint"
tprint (a)
</code>

Output:

<code>
"line"=1
"name"=""
"nodes":
  1:
    "line"=1
    "name"="foo"
    "nodes":
      1:
        "line"=1
        "name"="bar"
        "empty"=true
        "content"=""
        "attributes":
          "x"="2"
    "content"=""
"content"=""
</code>

You can see from the above that the "root" node is really just an unnamed node which is the placeholder for the top level nodes (ie. the first "real" node is a child of the root node). In this case the node "foo" is the first child of the root node.


name: utils.msgbox
prototype: response = utils.msgbox ( msg, title, type, icon, default )
summary: Display a message box and get a response
doc_name: lua_utils
description:
This lets you display a Windows message box (very similar to MsgBox in VBscript). The intention is to allow you to display (in a small dialog box), information of an urgent nature, or ask a yes/no type question.

The calling sequence is:

<code>
result = utils.msgbox ( msg, title, type, icon, default )
</code>

The only required argument is the message text itself, the others default to their first possible value. The first 4 arguments are string arguments, the last is a number.

<ul>

  <li/>msg = message to display (max 1000 characters)
  <li/>title = title of box - if nil, defaults to &quot;MUSHclient&quot; (max 100 characters)
  <li/>type = type of box (must be in lower case and exactly as shown here): 

<ul>
  <li/>&quot;ok&quot; - The message box contains one push button: OK. This is the default. 
  <li/>&quot;abortretryignore&quot; - The message box contains three push buttons: Abort, Retry, and Ignore. 
  <li/>&quot;okcancel&quot; - The message box contains two push buttons: OK and Cancel. 
  <li/>&quot;retrycancel&quot; - The message box contains two push buttons: Retry and Cancel. 
  <li/>&quot;yesno&quot; - The message box contains two push buttons: Yes and No. 
  <li/>&quot;yesnocancel&quot; - The message box contains three push buttons: Yes, No, and Cancel. 
</ul>
  <li/>icon = type of icon: 

<ul>
  <li/>&quot;!&quot; - An exclamation-point icon appears in the message box. This is the default.
  <li/>&quot;?&quot; - A question-mark icon appears in the message box.
  <li/>&quot;i&quot; - An icon consisting of a lowercase letter i in a circle appears in the message box.
  <li/>&quot;.&quot; - A stop-sign icon appears in the message box.
</ul>
  <li/>default = default button (1 - 3)

This sets the default button (the one with the focus) to be either button 1, 2 or 3. The default is the first button.
</ul>

Return value = (string) yes, no, ok, retry, ignore, cancel, abort

Example:

<code>
print (utils.msgbox (&quot;You are being paged&quot;, &quot;Warning!&quot;, &quot;ok&quot;, &quot;!&quot;, 1)) --&gt; ok
print (utils.msgbox (&quot;You are being paged&quot;)) --&gt; ok
print (utils.msgbox (&quot;Go ahead?&quot;, &quot;Question&quot;, &quot;yesno&quot;, &quot;?&quot;)) --&gt; yes / no
</code>

See also utils.umsgbox if you want to display a message in Unicode (UTF-8).


name: utils.inputbox
prototype: result = utils.inputbox ( msg, title, default, font, fontsize, extras )
summary: Display a message box and get free-format reply
doc_name: lua_utils
description:
This lets you display a Windows message box and accept a free-format reply (very similar to InputBox in VBscript). The intention is to allow you to display (in a small dialog box) a question and accept a typed response.

The calling sequence is:
<code>
result = utils.inputbox ( msg, title, default, font, fontsize, extras )
</code>

The only required argument is the message text itself.

<ul>
  <li/>msg = message to display (max 1000 characters)
  <li/>title = title of box - if nil, defaults to &quot;MUSHclient&quot; (max 100 characters)
  <li/>default = default text - defaults to no text
  <li/>font = font to use in response field - defaults to standard Windows font
  <li/>fontsize = size of font to use (ignored if no font supplied)
  <li/>extras = table of extra parameters
</ul>

The extra parameters (if supplied) is a table which can consist of one or more of:

<ul>
  <li/>box_width         --&gt; width of message box in pixels (min 180)
  <li/>box_height        --&gt; height of message box in pixels (min 125)
  <li/>prompt_width      --&gt; width of prompt text in pixels (min 10)
  <li/>prompt_height     --&gt; height of prompt text in pixels (min 12)
  <li/>reply_width       --&gt; width of reply in pixels (min 10)
  <li/>reply_height      --&gt; height of reply in pixels (min 10)
  <li/>max_length        --&gt; max characters they can type (min 1)
  <li/>validate          --&gt; validation function
  <li/>ok_button         --&gt; what text to put on the OK button (default: OK)
  <li/>cancel_button     --&gt; what text to put on the Cancel button (default: Cancel)
  <li/>ok_button_width    --&gt; the width of the OK button in pixels (default: 75)
  <li/>cancel_button_width--&gt; the width of the Cancel button in pixels (default: 75)
  <li/>read_only         --&gt; if true, input area is read-only
  <li/>no_default        --&gt; if true, pressing &lt;enter&gt; does not dismiss the dialog

</ul>

Examples of the extra parameters can be found here:

http://gammon.com.au/forum/?id=10644

The validate function (if used) should be a Lua function that takes a single argument (which is what was typed into the input box) and returns true if this reply was acceptable, and false if not. For example, you might return true if the reply was numeric, if a number was required. This function is called when they click the OK button.

Return value = what they typed, or nil if cancelled

Example:

<code>
print (utils.inputbox (&quot;What is your name?&quot;, &quot;Query&quot;, &quot;Nick&quot;, &quot;Courier&quot;, 9)) --&gt; Peter
</code>

There is also similar function which will handle a larger response: utils.editbox


name: utils.editbox
prototype: result = utils.editbox ( msg, title, default, font, fontsize, extras )
summary: Display a large message box and get free-format reply
doc_name: lua_utils
description:
This is almost identical to utils.inputbox, except that the response field:

<ul>
<li/>is much larger - for entering large amounts of text
<li/>has scroll bars - for scrolling through it
</ul>

Otherwise, the arguments are the same as for utils.inputbox.


name: utils.choose
prototype: result = utils.choose (msg, title, tbl, default)
summary: Display a combo box with choices in it
doc_name: lua_utils
description:
This displays a dialog box with a predetermined list of items for the user to choose from, in the form of a combo-box. If the user cancels the dialog box, or does not make a selection, nil is returned. Otherwise the key of the selected item is returned.

There are three similar functions that have the same arguments:

<ul>
  <li/>utils.choose - displays a dialog box with a combo-box in it (drop-down list)
  <li/>utils.listbox - displays a dialog box with a list control in it - single selection
  <li/>utils.multilistbox - displays a dialog box with a list control in it - multiple selections allowed
</ul>

The utils.listbox function would be more suitable for longer lists, but that is probably partly personal preference.

The utils.multilistbox function allows multiple selections, so this is useful when you want the user to be able to select multiple items.

The calling sequence is:

<code>
result = utils.choose ( msg, title, t, default )
</code>

The only required arguments are the message text and the table of choices (t).

<ul>
  <li/>msg = message to display (max 1000 characters)
  <li/>title = title of box - if nil, defaults to &quot;MUSHclient&quot; (max 100 characters)
  <li/>t - table of key/value pairs, as described below
  <li/>default = default key - defaults to no selection
</ul>

Return value = the key of what they selected, or nil if cancelled, or nothing selected. 

The third argument is a table of key/value pairs. The value is displayed, however the corresponding key is returned. The values are automatically sorted into ascending alphabetic order.

The fourth argument is the key (string or number) which corresponds to the wanted default selection. If it does not correspond to any key in the table then no item will be selected. For no default selection just pass nil as the default.

Example:


<code>
print (utils.choose (&quot;Your favourite&quot;, &quot;Foods ...&quot;, { &quot;apples&quot;, &quot;bananas&quot;, &quot;peaches&quot;, &quot;cream&quot; } ))
</code>

Possible returned values would be:

<ul>
  <li/>nil - if no choice made or dialog cancelled
  <li/>1 - apples chosen
  <li/>2 - bananas chosen
  <li/>3 - peaches chosen
  <li/>4 - cream chosen
</ul>

(Note that peaches would actually be shown 4th in the list as the list is sorted).

To convert from the key back to the value, simply index into your table. Eg.

<hr/>

<code>
t = { &quot;apples&quot;, &quot;bananas&quot;, &quot;peaches&quot;, &quot;cream&quot; } 
result = utils.choose (&quot;Your favourite&quot;, &quot;Foods ...&quot;, t)

if result then
  print (&quot;You chose&quot;, t [result])
else
  print &quot;Nothing chosen&quot;
end -- if
</code>

<hr/>

Keys and values can be either strings or numbers. MUSHclient will distinguish between strings and numbers which are the same (eg. &quot;10&quot; and 10 are considered different keys).

Here is an example of using string keys, and supplying a default choice:


<hr/>
<code>
t = { 
    fruit = &quot;apple&quot;, 
    vegetable = &quot;potato&quot;, 
    spice = &quot;pepper&quot;, 
    herb = &quot;parsley&quot;,
    } 
result = utils.choose (&quot;Choose a food&quot;, &quot;Foods ...&quot;, t, &quot;fruit&quot;)

if result then
  print (&quot;You chose key&quot;, result, &quot;which is&quot;, t [result])
else
  print &quot;Nothing chosen&quot;
end -- if
</code>
<hr/>


Possible returned values would be:

<ul>
  <li/>nil - if no choice made or dialog cancelled
  <li/>&quot;fruit&quot; - apple chosen
  <li/>&quot;vegetable&quot; - potato chosen
  <li/>&quot;spice&quot; - pepper chosen
  <li/>&quot;herb&quot;  - parsley chosen
</ul>


The return value will be one of the following types:


<ul>
  <li/>nil - if no selection made or dialog cancelled
  <li/>string - if an item with a string key is selected
  <li/>number - if an item with a numeric key is selected
</ul>


name: utils.listbox
prototype: result = utils.listbox (msg, title, tbl, default)
summary: Display a dialog box with choices in it in a single selection list box
doc_name: lua_utils
description:
This displays a dialog box with a predetermined list of items for the user to choose from, in the form of a single-selection listbox. If the user cancels the dialog box, or does not make a selection, nil is returned. Otherwise the key of the selected item is returned.

There are three similar functions that have the same arguments:

<ul>
  <li/>utils.choose - displays a dialog box with a combo-box in it (drop-down list)
  <li/>utils.listbox - displays a dialog box with a list control in it - single selection
  <li/>utils.multilistbox - displays a dialog box with a list control in it - multiple selections allowed
</ul>

The utils.listbox function would be more suitable for longer lists, but that is probably partly personal preference.

The utils.multilistbox function allows multiple selections, so this is useful when you want the user to be able to select multiple items.

The calling sequence is:

<code>
result = utils.listbox ( msg, title, t, default )
</code>

The only required arguments are the message text and the table of choices (t).

<ul>
  <li/>msg = message to display (max 1000 characters)
  <li/>title = title of box - if nil, defaults to &quot;MUSHclient&quot; (max 100 characters)
  <li/>t - table of key/value pairs, as described below
  <li/>default = default key - defaults to no selection
</ul>

Return value = the key of what they selected, or nil if cancelled, or nothing selected. 

The third argument is a table of key/value pairs. The value is displayed, however the corresponding key is returned. The values are automatically sorted into ascending alphabetic order.

The fourth argument is the key (string or number) which corresponds to the key of the wanted default selection. If it does not correspond to any key in the table then no item will be selected. For no default selection just pass nil as the default.

Example:


<code>
print (utils.listbox (&quot;Your favourite&quot;, &quot;Foods ...&quot;, { &quot;apples&quot;, &quot;bananas&quot;, &quot;peaches&quot;, &quot;cream&quot; } ))
</code>

Possible returned values would be:

<ul>
  <li/>nil - if no choice made or dialog cancelled
  <li/>1 - apples chosen
  <li/>2 - bananas chosen
  <li/>3 - peaches chosen
  <li/>4 - cream chosen
</ul>

(Note that peaches would actually be shown 4th in the list as the list is sorted).

To convert from the key back to the value, simply index into your table. Eg.

<hr/>

<code>
t = { &quot;apples&quot;, &quot;bananas&quot;, &quot;peaches&quot;, &quot;cream&quot; } 
result = utils.listbox (&quot;Your favourite&quot;, &quot;Foods ...&quot;, t)

if result then
  print (&quot;You chose&quot;, t [result])
else
  print &quot;Nothing chosen&quot;
end -- if
</code>

<hr/>

Keys and values can be either strings or numbers. MUSHclient will distinguish between strings and numbers which are the same (eg. &quot;10&quot; and 10 are considered different keys).

Here is an example of using string keys, and supplying a default choice:


<hr/>
<code>
t = { 
    fruit = &quot;apple&quot;, 
    vegetable = &quot;potato&quot;, 
    spice = &quot;pepper&quot;, 
    herb = &quot;parsley&quot;,
    } 
result = utils.listbox (&quot;Choose a food&quot;, &quot;Foods ...&quot;, t, &quot;fruit&quot;)

if result then
  print (&quot;You chose key&quot;, result, &quot;which is&quot;, t [result])
else
  print &quot;Nothing chosen&quot;
end -- if
</code>
<hr/>


Possible returned values would be:

<ul>
  <li/>nil - if no choice made or dialog cancelled
  <li/>&quot;fruit&quot; - apple chosen
  <li/>&quot;vegetable&quot; - potato chosen
  <li/>&quot;spice&quot; - pepper chosen
  <li/>&quot;herb&quot;  - parsley chosen
</ul>


The return value will be one of the following types:


<ul>
  <li/>nil - if no selection made or dialog cancelled
  <li/>string - if an item with a string key is selected
  <li/>number - if an item with a numeric key is selected
</ul>


name: utils.multilistbox
prototype: result = utils.multilistbox (msg, title, tbl, default)
summary: Display a dialog box with choices in it in a multiple selection list box
doc_name: lua_utils
description:
This displays a dialog box with a predetermined list of items for the user to choose from, in the form of a multiple-selection listbox. If the user cancels the dialog box, or does not make a selection, nil is returned. Otherwise the key of the selected item is returned.

There are three similar functions that have the same arguments:

<ul>
  <li/>utils.choose - displays a dialog box with a combo-box in it (drop-down list)
  <li/>utils.listbox - displays a dialog box with a list control in it - single selection
  <li/>utils.multilistbox - displays a dialog box with a list control in it - multiple selections allowed
</ul>

The utils.listbox function would be more suitable for longer lists, but that is probably partly personal preference.

The utils.multilistbox function allows multiple selections, so this is useful when you want the user to be able to select multiple items.

The calling sequence is:

<code>
result = utils.multilistbox ( msg, title, t, default )
</code>

The only required arguments are the message text and the table of choices (t).

<ul>
  <li/>msg = message to display (max 1000 characters)
  <li/>title = title of box - if nil, defaults to &quot;MUSHclient&quot; (max 100 characters)
  <li/>t - table of key/value pairs, as described below
  <li/>default = table of default keys (nil for no default selection)
</ul>

Return value = a table of the selected keys, or nil if nothing selected.

The third argument is a table of key/value pairs. The value is displayed, however the corresponding key is returned. The values are automatically sorted into ascending alphabetic order.

The fourth argument is a table of the keys of the wanted defaults. For no default selection just pass nil as the default.

Example:


<code>
t = { 
    fruit = &quot;apple&quot;, 
    vegetable = &quot;potato&quot;, 
    spice = &quot;pepper&quot;, 
    herb = &quot;parsley&quot;,
    } 

defaults = {
    fruit = true, 
    spice = true, 
    }

result = utils.multilistbox (
    &quot;Choose a food&quot;, 
    &quot;Foods ...&quot;, 
    t, 
    defaults
    )
</code>

Possible returned values would be:

<ul>
  <li/>nil - if dialog cancelled
  <li/>otherwise a table of chosen items (eg. { spice = true, fruit = true } ) - this table might be empty if nothing was chosen
</ul>

<hr/>

Keys and values can be either strings or numbers. MUSHclient will distinguish between strings and numbers which are the same (eg. &quot;10&quot; and 10 are considered different keys).


name: rex.new
prototype: re = rex.new (pattern, flags)
summary: Compiles a regular expression
doc_name: lua_rex
description:
This compiles a pattern, returning a regular expression object that can be used to test regular expressions. For example:

<code>
re = rex.new ("(.+) goes (.+)")
</code>

Flags are optional. If you want to use them you can use the rex.flags () function to convert various flags into numbers.


name: rex.flags
prototype: flag_table = rex.flags ()
summary: Returns a table of PCRE flags
doc_name: lua_rex
description:
This returns a table of PCRE flags. You can index into this to get various compile and runtime flags.

The following are valid compile-time flags:

<ul>
<li/>ANCHORED
<li/>CASELESS
<li/>DOLLAR_ENDONLY
<li/>DOTALL
<li/>EXTENDED
<li/>EXTRA
<li/>MULTILINE
<li/>NO_AUTO_CAPTURE
<li/>UNGREEDY
<li/>UTF8
</ul>


The following are valid execution-time flags:

<ul>
<li/>ANCHORED
<li/>NOTBOL
<li/>NOTEOL
<li/>NOTEMPTY
</ul>

An example of using the flags would be:

<code>
re = rex.new ("(.+) goes (.+)", rex.flags ().CASELESS)
</code>

This would make a caseless regular expression.


name: re:match
prototype: start, end, substrings = re:match (string, pos, flags)
summary: Matches a regexp to a string
doc_name: lua_rex
description:
This takes a regular expression object compiled previously with rex.new, and matches it against a target string.

The "pos" argument is optional, and specifies a 1-relative starting point for the match. If omitted, the whole string is tested. You can also supply a negative number to count from the right, eg. -10 would start 10 characters from the end of the string.

The "flags" argument is optional, and specifies execution flags, as described above.

Example:

<code>
re = rex.new ("(.+) goes (.+)")
s, e = re:match ("Nick goes East")
print (s, e) --> 1 14
</code>

If you are planning to do multiple matches against the same regular expression, it is faster to compile once only (ie. do rex.new once), and test multiple times.

However for once-off tests you can combine them both into the same line:

<code>
s, e = rex.new ("(.+) goes (.+)"):match ("Nick goes East")
print (s, e) --> 1 14
</code>

The third result returned is a table of capture patterns that have been matched. 

Example:

<code>
re = rex.new (&quot;(?P&lt;who&gt;.+) goes (?P&lt;where&gt;.+)&quot;)
s, e, t = re:match (&quot;Nick goes East&quot;)
print (s, e) --> 1 14
table.foreach (t, print) --> see below
</code>

Output from table.foreach:

1 Nick
2 East
where East
who Nick

This shows that the 2 capture patterns (the things in round brackets) have been captured in the table as index 1 and 2 (first and second pattern) and also under named indices "where" and "who" because we used named capture patterns in the regular expression.


name: re:exec
prototype: start, end, offsets = re:exec (string, pos, flags)
summary: Matches a regexp to a string, returning offsets
doc_name: lua_rex
description:
This takes a regular expression object compiled previously with rex.new, and matches it against a target string. It takes the same arguments are re:match, however the table returned as the 3rd result consists of pairs of offsets, rather than the strings themselves. 

For example:

<code>
re = rex.new ("(.+) goes (.+)")
s, e, t = re:exec ("Nick goes East")
print (s, e)  --> 1 14
table.foreach (t, print) --> see below
</code>

Output from table.foreach:

1 1
2 4
3 11
4 14

In this case we see that the first capture was from columns 1 to 4, and the second capture was from columns 11 to 14.


name: re:gmatch
prototype: result = re:gmatch (string, fun, count, flags)
summary: Matches a regexp to a string, applying a function
doc_name: lua_rex
description:
The gmatch function:

<ul>
<li/>Tries to match the regex re against string up to count times (or as many as possible if count is either not given or is not a positive number), subject to execution flags "flags".

<li/>Each time there is a match, fun is called as fun (m, t), where m is the matched string and t is a table of substring matches (this table contains false in the positions where the corresponding sub-pattern did not match.).

<li/>If fun returns a true value, then gmatch immediately returns.

<li/>gmatch returns the number of matches made.
</ul>

<code>
re = rex.new ("(\[A-Za-z\]+)")
n = re:gmatch ("Nick goes East", function (m, t) print (m) end )
print (n) --&gt; 3
</code>

Output from function during execution:

Nick
goes
East


name: bc.number
prototype: n = bc.number (n)
summary: Create a big number
doc_name: lua_bc
description:
Create a new big number based on n, where n can be a string if needed, to represent a large number.

eg.

<code>
a = bc.number ("1234.45534535345345434")
b = bc.number (5678)
</code>

If you are planning to use decimal places, you should call bc.digits first, otherwise the number may not be stored to the number of decimal places you wanted.

eg.

<code>
bc.digits (20)
a = bc.number ("1234.45534535345345434")
</code>


name: bc.digits
prototype: old = bc.digits (n)
summary: Digits after the decimal place
doc_name: lua_bc
description:
Do subsequent calculations to n digits after the decimal point.

eg. 

<code>
bc.digits (20)
a = bc.number (5.5) + 1
print (a)  --&gt; 6.50000000000000000000
</code>

Returns the old number of digits, so you could save them, change them, and then restore them.


name: bc.tostring
prototype: s = bc.tostring (n)
summary: Converts to a string
doc_name: lua_bc
description:
Converts a big number to a string (eg. for printing).

eg.

<code>
bc.digits (40)
a = bc.sqrt (2)
s = bc.tostring (a)
print (s)  --&gt; 1.4142135623730950488016887242096980785696
</code>


name: bc.sqrt
prototype: n = bc.sqrt (a)
summary: Square root
doc_name: lua_bc
description:
Returns the square root of a.

Example:

<code>
bc.digits (40)
i = bc.sqrt (2)
print (i) --&gt; 1.4142135623730950488016887242096980785696
</code>


name: coroutine.create
prototype: thread = coroutine.create (f)
summary: Creates a new coroutine thread
doc_name: lua_coroutines
description:
Creates a thread consisting of the body f.

<code>
thread = coroutine.create (f)
</code>

Then you can resume it with coroutine.resume.

For example:

<code>
function f (a, b, c)
  print (a, b, c)
end -- f

thread = coroutine.create (f)  -- thread will run function f
assert (coroutine.resume (thread, 1, 2, 3))  -- start thread, passing arguments: 1, 2, 3
</code>


name: coroutine.resume
prototype: ok, args = coroutine.resume (thread, v1, v2, ...)
summary: Start or resume a thread
doc_name: lua_coroutines
description:
Start or resume a thread created by coroutine.create. Any values supplied after the thread are returned as results from the coroutine.yield inside the thread. If this is the first call for this thread, the values are supplied to the function itself.

On success, returns true, followed by arguments to the coroutine.yield inside the function (if called), or the return  value of the function itself.

On failure, returns false followed by an error message.

<code>
assert (coroutine.resume (thread, 45, 67)) 
</code>


name: coroutine.status
prototype: s = coroutine.status (thread)
summary: Returns the status of a thread
doc_name: lua_coroutines
description:
Returns a string indicating the status of the thread. Raises an error if the argument is not a thread.

If it is, the values returned can be:

<ul>
<li/>running 
<li/>normal
<li/>suspended
<li/>dead
</ul>

A thread is "running" if coroutine.status is called from within the thread itself.

A thread is "normal" if the coroutine is active, but has resumed another coroutine.

It is "suspended" after being created but before it is resumed, and after yielding.

It is "dead" after it has returned from the entire function.

 
<code>
print (coroutine.status (thread)) --&gt; suspended
</code>


name: coroutine.wrap
prototype: f = coroutine.wrap (f)
summary: Creates a thread and returns a function to resume it
doc_name: lua_coroutines
description:
Creates a thread with body f, and then returns a function that can be used to resume the thread. This is a slightly simpler interface than the coroutine.create / coroutine.resume sequence, however it makes error management harder.

<code>
function f (s)
  print ("Entering f with value", s)
  v = coroutine.yield ()
  print ("After yield, v is", v)
  return 22
end -- f

resumer = coroutine.wrap (f) 
resumer (88)  -- start thread
resumer (99)  -- resume after yield

 --&gt;
 
Entering f with value 88
After yield, v is 99

</code>


name: coroutine.yield
prototype: args = coroutine.yield (v1, v2, ...)
summary: Yields execution of thread back to the caller
doc_name: lua_coroutines
description:
Yields execution back to the caller, effectively creating co-operative multi-tasking. Values supplied to yield are returned to coroutine.resume.

The coroutine cannot be running a C function, a metamethod, or an iterator.

Returns any arguments passed to the thread from coroutine.resume.

<code>
function f (s)
  print ("Entering f with value", s)
  v = coroutine.yield ("goat")
  print ("After yield, v is", v)
  return 22
end -- f

thread = coroutine.create (f)

ok, result = coroutine.resume (thread, 42) -- start it up
assert (ok, result) -- check ok
print (result) -- see what the yield returned

ok, result = coroutine.resume (thread, 55) -- resume it
assert (ok, result) -- check ok
print (result) -- see what the function returned


 --&gt;
 
Entering f with value 42
goat
After yield, v is 55
22

</code>


name: debug.debug
prototype: debug.debug ()
summary: Enters interactive debugging
doc_name: lua_debug
description:
Enters interactive debugging. MUSHclient has an interactive debug dialog box which lets you inspect local variables and upvalues, do a traceback, enter debugging commands, and then continue or abort the script.

<code>
debug.debug () -- enter debugger
</code>


name: debug.getfenv
prototype: t = debug.getfenv (obj)
summary: Returns the environment of an object
doc_name: lua_debug
description:
Returns the environment of object obj. This differs a bit from the base function getfenv, which takes a function or a level number, and converts the level number into a function. The debug version simply returns the environment of the argument, which is only meaningful for objects of type function, userdata or thread.


name: debug.gethook
prototype: f, mask, count = debug.gethook (thread)
summary: Returns the current hook settings
doc_name: lua_debug
description:
Returns the current hook settings as three values:

<ul>
<li/>Hook function
<li/>Mask
<li/>Count
</ul>

See debug.sethook for more details.

The thread argument is optional and defaults to the current thread.

<code>
f, mask, count = debug.gethook ()
print (f) --&gt; nil
print (mask) --&gt; ""
print (count) --&gt; 0
</code>


name: debug.getinfo
prototype: t = debug.getinfo (thread, f, what)
summary: Returns a table with information about a function
doc_name: lua_debug
description:
Returns a table with information about a function. The optional field "what" is a string indicating which values to return (can be more than one). If omitted, all is returned.

The thread argument is optional and defaults to the current thread.

What fields can be one or more of the following concatenated together:

<ul>
<li/>f - returns "func" field
<li/>l - returns "currentline" field
<li/>L - returns a table whose indices are the numbers of the lines that are valid on the function. (A valid line is a line with some associated code, that is, a line where you can put a break point. Non-valid lines include empty lines and comments.)
<li/>n - returns "name" and "namewhat" fields
<li/>S - returns "source", "short_src", "linedefined" and "what" fields
<li/>u - returns "nups" field
</ul>

The function name can be an integer representing the stack level, where 0 is debug.getinfo itself, 1 is the function that called debug.getinfo, 2 is the function that called that, and so on. Returns nil if the function number is larger than the number of functions on the stack.

Field meanings of the returned table are:

<ul>
<li/><b>source</b> - where the function was defined. If in a file, it is the file name prefixed by "@".

If the function was defined in a string (through loadstring) then "source" is this string.

If the function was defined interactively (through the lua.exe program) then source will be "stdin".

If the function was defined in a C program, then source will be "[C]".


<li/><b>short_src</b> - a shorter version of "source" (up to 60 characters), useful for error messages

<li/><b>linedefined</b> - the first line number, in the source, where this function was defined (for Lua functions).

<li/><b>lastlinedefined</b> - the last line number, in the source, where this function was defined (for Lua functions).

<li/><b>what</b> - what this function is. Can be "Lua" for a regular Lua function, "C" if it is a C function, or "main" if it is part of the main Lua chunk (ie. outside any function).

<li/><b>name</b> - an attempt to find the name of the function - may be nil. 

Since functions can have many names (by assigning a function to many variables) or no name, the name cannot always be determined.

Lua tries to find the name of the function by inspecting the call stack to find how the function was called. This can only work if debug.getinfo was called with a stack level number, not a function itself.

<li/><b>namewhat</b> - what the "name" field means. It can be "global", "local", "method", "field", or the empty string (""). The empty string means Lua did not find the name, and thus the name field will not be present.

<li/><b>nups</b> - the number of upvalues that this function has.

<li/><b>activelines</b> - a table of the active lines of the function, that is ones which have code on them, as opposed to blank lines or comments. Each entry in table contains the line number as a key, and true as the value.

<li/><b>currentline</b> - the line that is currently active (only applies to active functions, that is if the call to debug.getinfo is for a stack level).

<li/><b>func</b> - the function that is active at that stack level (if called with a stack level).

</ul>

<code>
t = debug.getinfo (table.sort)
table.foreach (t, print)

 --&gt;

source =[C]
what C
func function: 02061360
short_src [C]
currentline -1
namewhat 
linedefined -1
nups 0

-- another example, this time a user-defined function --

function f (a, b, c) print "hi" end
t = debug.getinfo (f, "flnSu")  --&gt; 'what' options explicitly mentioned
table.foreach (t, print)

 --&gt;
 
source  =stdin
what    Lua
func    function: 0x8079a40
name    f
nups    0
currentline     -1
namewhat        global
linedefined     1
short_src       stdin

-- this example prints the name of the currently-running function --

function myfunc () print (debug.getinfo (1, "n").name) end
myfunc ()  --&gt; myfunc

-- this example shows the active lines:

function f (a, b, c) 
print "hi" 
a = b + c
end
t = debug.getinfo (f, "L")
table.foreach (t.activelines, print)

 --&gt;
 
2	true
3	true
4	true

</code>


name: debug.getlocal
prototype: name, val = debug.getlocal (level, local)
summary: Returns name and value of a local variable
doc_name: lua_debug
description:
Returns the name and value of the local variable with the index 'local' of the function at 'level' on the stack.
See also debug.setlocal .

<code>
function f (a, b)
local c = 11
local i = 1

repeat
  name, val = debug.getlocal (1, i)
  if name then
    print ("index", i, name, "=", val)
    i = i + 1
  end -- if
until not name

end -- function f

f (22, 33)

 --&gt;

index 1 a = 22
index 2 b = 33
index 3 c = 11
index 4 i = 4
</code>


name: debug.getmetatable
prototype: t = debug.getmetatable (obj)
summary: Returns the metatable of the given object
doc_name: lua_debug
description:
Returns the metatable of the given object or nil if it does not have a metatable.

Bypasses the check for the "__metatable" entry.


name: debug.getregistry
prototype: t = debug.getregistry ()
summary: Returns the registry table
doc_name: lua_debug
description:
Returns the registry table. This is a special table used by C functions to store information it wants to keep isolated from Lua functions.

<code>
table.foreach (debug.getregistry (), print)

  --&gt;
  
FILE* table: 01B43F50
_LOADLIB table: 01B42BC0
mushclient.world table: 01B4BBC0
_LOADED table: 01B418C0
mushclient.document userdata: 017A8C58
pcre_regex_handle table: 01B4E830
</code>


name: debug.getupvalue
prototype: name, value = debug.getupvalue (level, upvalue)
summary: Returns the name and value of an upvalue
doc_name: lua_debug
description:
Similar to debug.getlocal, returns the names and values of the upvalues for the nominated function. See also debug.setupvalue.

<code>
function newCounter ()
  local n = 0
  return function ()  -- anonymous function
    n = n + 1
    return n
    end -- function
end -- newCounter 

c = newCounter ()
c ()  -- count a couple of times
c ()

-- show upvalues in c

local i = 1

repeat
  name, val = debug.getupvalue (c, i)
  if name then
    print ("index", i, name, "=", val)
    i = i + 1
  end -- if
until not name

 --&gt;
 
 index 1 n = 2
</code>

In this example the function c is a closure (with associated upvalue "n").

NOTE: Lua does not let you see or change upvalues for C functions (eg. string.gfind).


name: debug.setfenv
prototype: obj = debug.setfenv (object, table)
summary: Sets the environment of an object
doc_name: lua_debug
description:
Sets the environment of the given object to the given table. Returns object. Similarly to debug.getfenv, this function takes a raw object (unlike the base setfenv function which can also take a function level).


name: debug.sethook
prototype: debug.sethook (thread, f, mask, count)
summary: Sets a debug hook function
doc_name: lua_debug
description:
Sets the function f as a hook to be called when the "mask" condition is satisfied.

If count is non-zero, it is called after every "count" instructions.

The thread argument is optional and defaults to the current thread.

If called without arguments, turns off the hook.

Mask can be one or more of:

<ul>
<li/>c - called every time Lua calls a function
<li/>r - called every time Lua returns from a function
<li/>l - called every time Lua enters a new line of code
</ul>

The mask can be the empty string if you simply want to hook after "count" instructions.

The function f is called with its first parameter being a string, which can be one of:

<ul>
<li/>call
<li/>return
<li/>tail return
<li/>line
<li/>count
</ul>

In the case of "line" events it gets a second parameter, being the new line number.

Inside the hook you can use debug.getinfo with level 2 to find information about the running function. (Level 0 is getinfo, and level 1 is the hook function). In the case of "tail return" however debug.getinfo will not return valid information.

Here is an example of setting a hook to stop a runaway function from executing for too long:

<code>
function test ()
  a = 0
  for i = 0, 1000 do
    a = a + i
  end -- for
end -- test

function hook (why)
  error ("hook reached: " .. why)
end -- hook

debug.sethook (hook, "", 100)

test () --&gt; error:  hook reached: count
</code>

In this case, the hook stopped execution after 100 instructions.

This second example uses a "call" hook to display when each new function is entered:

<code>
function f ()
  function g ()
  end -- g

 g () 
 g ()
end -- f

function hook (why)
  print ("hook reached: ", why)
  print ("function =", debug.getinfo (2, "n").name)
end -- hook

debug.sethook (hook, "c", 0)

f ()

 --&gt;
 
hook reached:  call
function = f
hook reached:  call
function = g
hook reached:  call
function = g
</code>


name: debug.setlocal
prototype: debug.setlocal (level, local, value)
summary: Sets the value of the local variable
doc_name: lua_debug
description:
Sets the value of the local variable with the index 'local' of the function at 'level' on the stack. See also debug.getlocal.


name: debug.setmetatable
prototype: object = debug.setmetatable (object, table)
summary: Sets the metatable for an object
doc_name: lua_debug
description:
Sets the metatable for the given object to the given table (which can be nil).

Bypasses the check for the "__metatable" entry.

Returns the object.


name: debug.setupvalue
prototype: debug.setupvalue (function, upvalue, value)
summary: Sets an upvalue for a function
doc_name: lua_debug
description:
Similar to debug.setlocal, sets the values of the upvalue for the nominated function. See also debug.getupvalue.


name: debug.traceback
prototype: s = debug.traceback ( [thread,] message [, level])
summary: Returns a string with a traceback of the stack call
doc_name: lua_debug
description:
Returns a string with a traceback of the stack call. An optional message string is prepended to the beginning of the traceback message.

<code>
function f ()
  function g ()
  print (debug.traceback ("traceback in g"))
  end -- g
  g ()
end -- f

f ()

 --&gt;
 
traceback in g
stack traceback:
        stdin:3: in function `g'
        stdin:6: in function `f'
        stdin:1: in main chunk
        [C]: ?
</code>

You can optionally supply a thread (coroutine) to be traced. This is useful if you get an error after calling coroutine.resume.

An  optional level number tells at which level to start the tracekback - the default is 1 which is the function calling traceback.


name: io.close
prototype: io.close (f)
summary: Closes a file
doc_name: lua_io
description:
Equivalent to f:close (). Without f supplied closes the default output file.

<code>
io.close (f) -- closes the file descriptor f
</code>


name: io.input
prototype: f = io.input (filename)
summary: Opens filename for input in text mode
doc_name: lua_io
description:
Opens filename for input in text mode. Raises an error if it cannot.
If opened OK returns a handle to the opened file, and makes it the default input file.

If called with no argument, returns the handle to the default input file.

If called with a file handle, sets the default input file to that handle.

<code>
prev = io.input ()  -- save current input file
f = io.input ("test.txt") --&gt; handle to new file
f:close ()  -- close that file now
io.input (prev) -- restore previous input file
</code>


name: io.lines
prototype: it = io.lines (filename)
summary: Returns an iterator function for reading a named file line-by-line
doc_name: lua_io
description:
Opens filename for input in text mode. Raises an error if it cannot.

If opened OK returns an iterator function that reads the file line-by-line.

At end of file, returns nil and closes the file.

If filename not supplied, uses the default input file.

<code>
for line in io.lines ("test.txt") do
  print (line)
end 

 --&gt; Entire contents of file listed
</code>


name: io.open
prototype: f = io.open (filename, mode)
summary: Opens a file
doc_name: lua_io
description:
Opens a file and returns a file handle for working with it.

Modes can be a string which is:

<ul>
<li/>r - read mode
<li/>w - write mode (overwrites existing)
<li/>a - append mode (appends to existing)
<li/>b - binary mode
<li/>r+ - update mode (existing data preserved)
<li/>w+ - update mode (existing data erased)
<li/>a+ - append update mode (existing data preserved, append at end of file only)
</ul>

If the file cannot be opened this function does not raise an error (unlike io.input and io.output) but returns 3 things:

<ul>
<li/>nil
<li/>An error message (string)
<li/>An error code (number)
</ul>

Thus a sensible thing to do is wrap the io.open call with an assert, as in the example:

<code>
f = assert (io.open ("test.txt", "r"))  -- open it
s = f:read ("*a")  -- read all of it
print (s)  -- print out
f:close ()  -- close it
</code>


name: io.output
prototype: f = io.output (filename)
summary: Opens a file for output
doc_name: lua_io
description:
Opens filename for output in text mode. Raises an error if it cannot.

If opened OK returns a handle to the opened file, and makes it the default output file.

If called with no argument, returns the handle to the default output file.

If called with a file handle, sets the default output file to that handle.

<code>
f = io.output ("test.txt") --&gt; handle to new file
f:write ("some data here") -- write to it
f:close ()  -- close that file now
</code>


name: io.popen
prototype: f = io.popen (command, mode)
summary: Creates a pipe and executes a command
doc_name: lua_io
description:
Creates a pipe and executes a command. Mode can be one of:

<ul>
<li/>"r" - The calling process can read the spawned command’s standard output via the returned stream. This is the default.

<li/>"w" - The calling process can write to the spawned command’s standard input via the returned stream.

<li/>"b" - Open in binary mode.

<li/>"t" - Open in text mode.
</ul>

However io.popen is not supported under the version compiled into MUSHclient, so don't get too excited. :)

This is an example of using popen under the Linux Lua executable:

<code>
 f = assert (io.popen ("ls -l"))
  
 for line in f:lines() do
   print(line)
 end -- for loop
   
 f:close()
</code>

An alternative to using pipes, if you want to capture operating system output, is to redirect command output to a temporary file, like this:

<code>
-- get a temporary file name
n = os.tmpname ()

-- execute a command
os.execute ("dir &gt; " .. n)

-- display output
for line in io.lines (n) do
  print (line)
end

-- remove temporary file
os.remove (n)
</code>


name: io.tmpfile
prototype: f = io.tmpfile ()
summary: Returns a handle to a temporary file
doc_name: lua_io
description:
Returns a handle to a temporary file, opened in update mode. Automatically removed when the program ends.


<code>
f = assert (io.tmpfile ()) -- open temporary file
f:write ("some data here")  -- write to it
f:seek ("set", 0) -- back to start
s = f:read ("*a")  -- read all of it back in
print (s)  -- print out
f:close ()  -- close file

--&gt;

some data here

</code>

If the file cannot be opened the function returns 3 things:

<ul>
<li/>nil
<li/>An error message (string)
<li/>An error code (number)
</ul>


name: io.stdin
prototype: io.stdin
summary: File handle for standard input file
doc_name: lua_io
description:
A file descriptor representing the current stdin (input) file handle.

This is a userdata, not a function.


name: io.stdout
prototype: io.stdout
summary: File handle for standard output file
doc_name: lua_io
description:
A file descriptor representing the current stdout (output) file handle.

This is a userdata, not a function.


name: io.stderr
prototype: io.stderr
summary: File handle for standard error file
doc_name: lua_io
description:
A file descriptor representing the current stderr (error) file handle.

This is a userdata, not a function.


name: io.type
prototype: s = io.type (f)
summary: Returns type of file handle
doc_name: lua_io
description:
Returns a string which is one of:

<ul>
<li/>file - an open file handle
<li/>closed file - a closed file handle
<li/>nil - not a file handle
</ul>

<code>
f = io.tmpfile ()
print (io.type (f))
f:close ()
print (io.type (f))

--&gt;

file
closed file
</code>


name: f:close
prototype: f:close ()
summary: Closes a file
doc_name: lua_io
description:
Closes the file f.

<code>
f:close () -- closes the file descriptor f
</code>

If the close was successful the function returns true.

If the file cannot be closed the function returns 3 things:

<ul>
<li/>nil
<li/>An error message (string)
<li/>An error code (number)
</ul>


name: f:lines
prototype: it = f:lines ()
summary: Returns an iterator function for reading the file line-by-line
doc_name: lua_io
description:
Returns an iterator function that reads the open file line-by-line.

At end of file, returns nil.

It does not close the file.

<code>
f = io.input ("test.txt")
for line in f:lines () do
  print (line)
end 
f:close ()  -- close that file now

 --&gt; Entire contents of file listed
</code>


name: f:read
prototype: v1, v2 ... = f:read (format1, format2, ...)
summary: Reads the file according to the specified formats
doc_name: lua_io
description:
Reads the file f according to the given formats. Each format returns a string, a number, or nil and an error code if it fails (see below). The formats are:

<ul>
<li/>*n - reads a number and returns it
<li/>*a - reads the entire file from the current position
<li/>*l - (default) - reads the next line, returns nil on EOF
<li/>number - returns a string with up that many characters in it, or nil on EOF
</ul>

<code>
f = io.input ("test.txt")
repeat
  s = f:read ("*l") -- read one line
  if s then  -- if not end of file (EOF)
   print (s) -- print that line
  end
until not s  -- until end of file

f:close ()  -- close that file now
</code>

If the file cannot be read the function returns 3 things:

<ul>
<li/>nil
<li/>An error message (string)
<li/>An error code (number)
</ul>


name: f:seek
prototype: n = f:seek (whence, offset)
summary: Sets and gets the current file position
doc_name: lua_io
description:
Sets and gets the current file position.

f:seek () --&gt; returns the current file position

When setting a position you can supply a string which is one of:

<ul>
<li/>"set" - from beginning of file
<li/>"cur" - from current position
<li/>"end" - from end of file
</ul>

The offset is a number from the base position.


<code>
f:seek ("set", 0)     -- go to start of file
f:seek ("end", -100)  -- go to 100 bytes from end of file
f:seek ("cur", 50)    -- go forwards 50 bytes
</code>


name: f:setvbuf
prototype: f:setvbuf (mode, size)
summary: Sets the buffering mode for an output file
doc_name: lua_io
description:
Sets the buffering mode for an output file. There are three available modes, which are supplied as strings:

<ul>
<li/>"no": no buffering; the result of any output operation appears immediately.

<li/>"full": full buffering; output operation is performed only when the buffer is full (or when you explicitly flush the file (see io.flush)).

<li/>"line": line buffering; output is buffered until a newline is output or there is any input from some special files (such as a terminal device).

</ul>

For the last two cases, size specifies the size of the buffer, in bytes. The default is an appropriate size.


name: f:write
prototype: f:write (v1, v2, v3, ...)
summary: Writes to a file
doc_name: lua_io
description:
Writes arguments to the file. They must be strings or numbers.

<code>
f:write ("hi there", 42, "some more data") 
</code>

If the write was successful the function returns true.

If the file cannot be written the function returns 3 things:

<ul>
<li/>nil
<li/>An error message (string)
<li/>An error code (number)
</ul>

A sensible thing to do would be to check the return code like this:

<code>
assert (f:write ("hi there", 42, "some more data"))
</code>


name: math.acos
prototype: v = math.acos (v)
summary: Arc cosine
doc_name: lua_math
description:
Arc cosine of v. (Inverse operation of math.cos (v)).

<code>
math.deg (math.acos (0.5)) --&gt; 60
</code>


name: math.deg
prototype: deg = math.deg (r)
summary: Convert from radians to degrees
doc_name: lua_math
description:
Convert v from radians to degrees. Note that math.rad is the inverse operation.

<code>
math.deg (1.0471975511966)  --&gt; 60
</code>


name: math.exp
prototype: v = math.exp (v)
summary: Raises e to a power
doc_name: lua_math
description:
Compute e to the power v. Note that math.log is the inverse operation.

<code>
math.exp (1) --&gt; 2.718281828459 (e itself in this case)
</code>


name: math.frexp
prototype: m, n = math.frexp (v)
summary: Break number into mantissa and exponent
doc_name: lua_math
description:
The frexp function breaks down the floating-point value (v) into a mantissa (m) and an exponent (n), such that the absolute value of m is greater than or equal to 0.5 and less than 1.0, and v = m * 2^n. 

Note that math.ldexp is the inverse operation.

<code>
m, n = math.frexp (1.23456e24)
print (m) --&gt; 0.51060204851673
print (n) --&gt; 81
print ( 0.51060204851673 * 2^81 )  --&gt; 1.23456e+024
</code>


name: math.huge
prototype: v = math.huge
summary: A huge value
doc_name: lua_math
description:
The value HUGE_VAL, a value larger than or equal to any other numerical value. Note that this is a number, not a function.

<code>
math.huge --&gt; 1.#INF
</code>


name: math.ldexp
prototype: v = math.ldexp (m, n)
summary: Compute m* 2^n
doc_name: lua_math
description:
The ldexp function returns the value of m * 2^n.

Note that math.frexp is the inverse operation.

<code> 
math.ldexp (0.51060204851673, 81)   --&gt; 1.23456e+024
math.ldexp (math.frexp (23452345) ) --&gt; 23452345
</code>


name: math.log
prototype: v = math.log (v)
summary: Natural log
doc_name: lua_math
description:
Natural log of v. Note that math.exp is the inverse operation.

<code>
math.log (123456) --&gt; 11.723640096265
math.exp (math.log (123456))  --&gt; 123456
</code>


name: math.log10
prototype: v = math.log10 (v)
summary: Log to the base 10
doc_name: lua_math
description:
Log to the base 10 of v.

<code>
math.log10 (123456) --&gt; 5.0915122016278
10 ^ 5.0915122016278 --&gt; 123456.00000001 (slight rounding error)
</code>


name: math.modf
prototype: i, f = math.modf (v)
summary: Returns the integral and fractional part of its argument
doc_name: lua_math
description:
Returns two numbers, the integral part of v and the fractional part of v

<code>
math.modf (10.2) --&gt; 10  0.2
</code>


name: math.pi
prototype: pi = math.pi
summary: The value of pi
doc_name: lua_math
description:
A variable representing the value of pi (not a function).

<code>
print (math.pi) --&gt; 3.1415926535898 
</code>


name: math.rad
prototype: r = math.rad (deg)
summary: Convert degrees to radians
doc_name: lua_math
description:
Convert v from degrees to radians. Note that math.deg is the inverse operation.

<code>
math.rad (60) --&gt; 1.0471975511966
assert (math.pi / 180 == math.rad (1))   --&gt; (they are the same)
</code>


name: math.random
prototype: v = math.random (n, u)
summary: Generate a random number
doc_name: lua_math
description:
With no arguments, returns a random number in the range [0, 1). That is, zero up to but excluding 1.

With 1 argument, returns an integer in the range [1, n]. That is from 1 up to and including n.

With 2 arguments, returns an integer in the range [n, u]. That is from n up to and including u.

Use math.randomseed to seed the generator.

<code>
math.random () --&gt; 0.30195013275552 (for example)
math.random (5)  --&gt; (a number from 1 to 5)
math.random (4, 8)  --&gt; (a number from 4 to 8)
</code>

Also see the world.MtRand function for random numbers generated by the Mersenne Twister algorithm.


name: math.randomseed
prototype: math.randomseed (n)
summary: Seeds the random number generator
doc_name: lua_math
description:
Seeds the random number generator with an integer. Re-seed with the same number to regenerate the same sequences by calling math.random. 

Seeding with os.time () is a common technique to make random numbers different each time. Be aware however that for cryptographic purposes, the time of day is hardly a secret.

<code>
math.randomseed (44)    -- fixed random seed
math.randomseed (os.time ())  -- randomize from whatever the time is
</code>

Also see the world.MtSrand function for seeding the Mersenne Twister random number generator.


name: os.clock
prototype: cpu = os.clock ()
summary: Amount of elapsed/CPU time used (depending on OS)
doc_name: lua_os
description:
Returns the approximate amount of CPU time used by the current process in seconds.

<code>
print (os.clock () / 60 / 60) --&gt; 34.381006944444 (hours)
</code>

WARNING - under Linux and Mac OS os.clock returns the CPU time used.  However, under Windows it returns the elapsed time that the process has been running (not the CPU time used). This is because the operating system call "clock" works differently under Windows.


name: os.date
prototype: s = os.date (format, time)
summary: Formats a date/time string
doc_name: lua_os
description:
Returns a string with the date and time formatted according to the format given. If no time is supplied defaults to the current time.

The format string can consist of "*t" on its own, or literal strings, mixed with the following directives:

<code>
%a - Abbreviated weekday name (eg. Wed)
%A - Full weekday name (eg. Wednesday)
%b - Abbreviated month name (eg. Sep)
%B - Full month name (eg. September)
%c - Date and time representation appropriate for locale (eg. 23/04/07 10:20:41)
         (Standard date and time string ) - see below for using os.setlocale to get the correct locale.
%d - Day of month as decimal number (01 - 31)
%H - Hour in 24-hour format (00 - 23)
%I - Hour in 12-hour format (01 - 12)
%j - Day of year as decimal number (001 - 366)
%m - Month as decimal number (01 - 12)
%M - Minute as decimal number (00 - 59)
%p - Current locale’s A.M./P.M. indicator for 12-hour clock (eg. AM/PM)
%S - Second as decimal number (00 - 59)
%U - Week of year as decimal number, with Sunday as first day of week 1 (00 - 53)
%w - Weekday as decimal number (0 - 6; Sunday is 0)
%W - Week of year as decimal number, with Monday as first day of week 1 (00 - 53)
%x - Date representation for current locale (Standard date string)
%X - Time representation for current locale (Standard time string)
%y - Year without century, as decimal number (00 - 99)  (eg. 07)
%Y - Year with century, as decimal number (eg. 2007)
%Z - Time-zone name or abbreviation; no characters if time zone is unknown
%% - Percent sign
</code>

If you use "*t" you get a table consisting of:

<ul>
<li/>sec  (0 to 59)
<li/>min  (0 to 59)
<li/>hour (0 to 23)
<li/>day  (1 to 31)
<li/>month (1 to 12)
<li/>year  (1900 onwards)
<li/>wday (Sunday is 1, Monday is 2 etc.)
<li/>yday (January 1st is 1, etc.)
<li/>isdst (true if Daylight Savings Time)
</ul>

Examples:

<code>
print (os.date ("%x")) --&gt; 25/04/07
print (os.date ("%c")) --&gt; 25/04/07 10:10:05
print (os.date ("%A, %m %B %Y")) --&gt; Wednesday, 04 April 2007

t = os.date ("*t") --&gt; produces a table like this:

  t.sec=18
  t.min=13
  t.hour=10
  t.day=25
  t.month=4
  t.year=2007
  t.wday=4
  t.yday=115
  t.isdst=false
</code>

<i>Locale note</i> - it seems that doing this helps set the locale appropriately:

<code>
os.setlocale ("", "time")
</code>


name: os.difftime
prototype: n = os.difftime (t1, t2)
summary: Calculates a time difference in seconds
doc_name: lua_os
description:
Returns the number of seconds from time t1 to time t2.

In other words, the result is t1 - t2.

<code>
tstart = os.time ()
-- do something lengthy here ..
tend = os.time ()
print (os.difftime (tend , tstart)) --&gt; 3
</code>

When using MUSHclient (ie. this is not standard Lua) you can get better resolution by using GetInfo (which uses the Windows "high performance" timer), like this:

<code>
tstart = GetInfo (232)  -- get high-resolution timer value
-- do something lengthy here ..
tend = GetInfo (232)    
print (string.format ("Time taken = %1.3f seconds", tend - tstart))
</code>


name: os.execute
prototype: status = os.execute (command)
summary: Executes an operating system command
doc_name: lua_os
description:
Passes 'command' to the operating system shell for execution. Returns a status code.

<code>
status = os.execute ("dir") --&gt; (directory listing whizzes by)
</code>

Here is a method of capturing the output to a file, and reading it in:

<code>
-- get a temporary file name
n = os.tmpname ()

-- execute a command
os.execute ("dir &gt; " .. n)

-- display output
for line in io.lines (n) do
  print (line)
end

-- remove temporary file
os.remove (n)
</code>


name: os.exit
prototype: os.exit (n)
summary: Attempts to terminate the process
doc_name: lua_os
description:
Terminates the host program with the return code n (in standard Lua).

However, os.exit is does not do that in MUSHclient. It will raise an error if called ("'os.exit' not implemented in MUSHclient"). This is because doing an immediate exit bypasses all checks to save open documents, save plugin states, and so on.


name: os.getenv
prototype: os.getenv (v)
summary: Returns an operating system environment variable
doc_name: lua_os
description:
Returns the environment variable v, or nil if undefined.

<code>
print (os.getenv ("PATH")) --&gt; (my PATH variable)
</code>


name: os.remove
prototype: ok, message = os.remove (filename)
summary: Deletes a file
doc_name: lua_os
description:
Deletes the file. On success, returns true.

If it cannot, it returns nil followed by an error message.

<code>
os.remove ("test.txt") --&gt; true
ok, err = os.remove ("test.txt") --&gt; nil, test.txt: No such file or directory
</code>


name: os.rename
prototype: ok, message = os.rename (oldname, newname)
summary: Renames a file
doc_name: lua_os
description:
Renames a file. On success, returns true.

If it cannot, it returns nil followed by an error message.

<code>
os.rename("test.txt", "test2.txt") --&gt; true
os.rename("test.txt", "test2.txt") --&gt; nil, test.txt: File exists 
</code>


name: os.setlocale
prototype: name = os.setlocale (locale, category)
summary: Sets the current locale to the supplied locale
doc_name: lua_os
description:
Sets the current locale to the supplied locale. Category, which is optional, is a string which is one of:

<ul>
<li/>"all" (the default)
<li/>"collate"
<li/>"ctype"
<li/>"monetory"
<li/>"numeric"
<li/>"time"
</ul>

Returns the name of the new locale, or nil if invalid.

<code>
print (os.setlocale ("en", "collate")) --&gt; English_United States.1252
</code>

Hint: I found that in Australia, the default in Lua was to use the USA time format (MM/DD/YY) rather than the local format (DD/MM/YY) when displaying dates with os.date. This line seemed to fix that:

<code>
print (os.setlocale ("", "time")) --&gt; English_Australia.1252
</code>

According to the help file "If locale points to an empty string, the locale is the implementation-defined native environment.". Thus the empty locale string seemed take the country default.


name: os.time
prototype: time = os.time (t)
summary: Returns the current time or calculates the time in seconds from a table
doc_name: lua_os
description:
Returns the current time if no argument supplied. The time is in seconds from the start of the current epoch.

On Windows, the function returns the number of seconds elapsed since midnight (00:00:00), January 1, 1970, coordinated universal time, according to the system clock.

If an argument is supplied it must be a table with at least the entries:

<ul>
<li/>year
<li/>month
<li/>day
</ul>

The table can also have the entries:


<ul>
<li/>hour
<li/>min
<li/>sec
<li/>isdst
</ul>

This table can be produced by calling: os.date ("*t")

<code>
print (os.time { year = 2004, month = 8, 
                 day = 30, hour = 6, min = 32, sec = 1, dst = true }) --&gt; 1093811521
print (os.date ("%x %X", 1093811521))  --&gt; 30/08/04 06:32:01                 
</code>


name: os.tmpname
prototype: s = os.tmpname ()
summary: Returns a name for a temporary file
doc_name: lua_os
description:
Returns a string with a name for a temporary file. Considered unsafe in an untrusted environment because someone may substitute a different file for the one whose name is returned to you, in the small window of time between obtaining the file name, and opening the file.

<code>
print (os.tmpname ()) --&gt; /temp/s56.2
</code>


name: package.config
prototype: package.config
summary: Package configuration string
doc_name: lua_package
description:
This is a string containing the various character used by the package manager to handle loading packages:

The default entries are:

<code>
\  --&gt; directory seperator
;  --&gt; path seperator
?  --&gt; path mark
!  --&gt; execution directory
-  --&gt; ignore mark - ignore everything before it to build a function name
</code>


name: package.cpath
prototype: package.cpath
summary: Search path used for loading DLLs using the "require" function
doc_name: lua_package
description:
This is a string containing the search path used for loading DLLs when using the "require" function. Default values are:

<code>
.\?.dll;!\?.dll;!\loadall.dll
</code>

In the above, the package name (eg. "socket") will replace the "?" characters and the current executable pathname (eg. "c:\mushclient") will replace the "!" characters.


name: package.loaded
prototype: package.loaded
summary: Table of loaded packages
doc_name: lua_package
description:
A table of the packages that are already loaded. Built-in packages (eg. table, string) are also in this table.

<code>
table.foreach (package.loaded, print)

  --&gt;

string	table: 00301370
package	table: 00302C70
_G	table: 00300200
os	table: 003034E0
table	table: 00302560
math	table: 00304B00
coroutine	table: 00301040
debug	table: 00304340
io	table: 00303D60
</code>


name: package.loaders
prototype: package.loaders
summary: Table of package loaders
doc_name: lua_package
description:
This is a table of the loaders that Lua calls when handling the "require" function. As defined in the source code they are presently done in this order:

<ul>
<li/>Preloader
<li/>Lua loader
<li/>DLL loader
<li/>All-in-one loader
</ul>

You could conceivable alter the behaviour of the "require" function be re-odering the loaders (eg. load DLLs before Lua code), deleting a loader, or adding your own.

The existing loaders appear to push a string describing what files they failed to load (which you can see if you load a non-existant package), so any loaders you write yourself could return the loaded function on success, and an error string on failure.


name: package.loadlib
prototype: f = package.loadlib (libraryname, funcname)
summary: Loads a dynamic link library (DLL)
doc_name: lua_package
description:
Loads the dynamic library (DLL), and tries to find the entrypoint named "funcname".

On success returns the function funcname.

On failure returns nil plus 2 error messages.

The error might be "The specified <b>module</b> could not be found." if the DLL is not found. You may also get this message if the DLL is dependant on another DLL and that other DLL cannot be found. Use a "dependency checker" to see what DLLs the target DLL might require. If you are certain that the DLL you are requesting exists, then the problem is probably a dependency.

The error might be "The specified <b>procedure</b> could not be found." if the function is not found in the DLL. You may also get this message if the DLL is dependant on another DLL and some entry points in that other DLL cannot be found. Use a "dependency checker" to see whether all required entry points have been resolved. If you are certain that the entry point that you are requesting exists in the target DLL, then the problem is probably a dependency from the target DLL to another DLL.

You would normally then execute the function (as in the example below) to get it to install the Lua functions into the script space. 

<code>
f = assert (package.loadlib ("luacom.dll", "luacom_openlib"))
f () -- execute function: luacom_openlib
</code>

Or, more briefly:

<code>
assert (package.loadlib ("luacom.dll", "luacom_openlib")) ()
</code>


name: table.concat
prototype: s = table.concat (t, sep, start, end)
summary: Concatenates table items together into a string
doc_name: lua_tables
description:
Returns the (numeric) entries in the table t, concatenated together with "sep" as the separator, starting at index 'start' and ending at index 'end'. The entries are returned as a single string variable. Contrast this to the "unpack" function which returns a table as individual variables.

Start defaults to 1 and end the table size.
Sep defaults to an empty string.

<code>
t = { "the", "quick", "brown", "fox" }
print (table.concat (t, ';')) --&gt; the;quick;brown;fox
</code>


name: package.path
prototype: package.path
summary: Search path used for loading Lua code using the "require" function
doc_name: lua_package
description:
This is a string containing the search path used for loading Lua code when using the "require" function. Default values are:

<code>
.\?.lua;!\lua\?.lua;!\lua\?\init.lua;!\?.lua;!\?\init.lua
</code>

In the above, the package name (eg. "socket") will replace the "?" characters and the current executable pathname (eg. "c:\mushclient") will replace the "!" characters.


name: package.preload
prototype: package.preload
summary: A table of special function loaders
doc_name: lua_package
description:
A table of functions that can be used as loaders. If you want to make a special loader for your package you can insert it into the package.preload table. For example:

<code>
package.preload ["foo"] = function () print "loading foo" end
require "foo"  --&gt; loading foo
</code>

In this example, when we required the package foo, the function was called.


name: package.seeall
prototype: package.seeall (module)
summary: Sets a metatable for the module so it can see global variables
doc_name: lua_package
description:
Sets a metatable for module with its __index field referring to the global environment, so that this module inherits values from the global environment. To be used as an option to function module. For example:

<code>
module ("foo", package.seeall)
</code>

The module code applies the function package.seeall to the new package (foo) and thus now package foo can access global variables.


name: table.foreachi
prototype: val = table.foreachi (t, f)
summary: Applies a function to each item in a numerically-keyed table
doc_name: lua_tables
description:
Executes f for each element in table t.

Function f is called with the arguments (key, value).

If f returns a non-nil value the loop is broken, and this value is returned as the result from table.foreach. Effectively this could be used to find an element inside a table matching a certain condition.

Similar to table.foreach, except that only numeric keys in the range 1 to n are processed.

<code>
t = { "the", "quick", "brown", "fox", name = 'Nick' }
table.foreachi (t, print)

 --&gt;

1 the
2 quick
3 brown
4 fox
</code>

In this example the entry for "name = 'Nick'" was not returned because it did not have a numeric key.


<b>Warning</b> the use of table.foreachi is deprecated. This means it may not be available in future versions of Lua. You are recommended to rewrite such uses by using the 'ipairs' function. For example:

<code>
for k, v in ipairs (t) do
  f (k, v)
end 
</code>


name: table.foreach
prototype: val = table.foreach (t, f)
summary: Applies a function to each item in a table
doc_name: lua_tables
description:
Executes f for each element in table t. 

Function f is called with the arguments (key, value).

If f returns a non-nil value the loop is broken, and this value is returned as the result from table.foreach. Effectively this could be used to find an element inside a table matching a certain condition.

<code>
t = { "the", "quick", "brown", "fox", name = "Nick" }
table.foreach (t, print)

 --&gt;
 
1 the
2 quick
3 brown
4 fox
name Nick
</code>

<b>Warning</b> the use of table.foreach is deprecated. This means it may not be available in future versions of Lua. You are recommended to rewrite such uses by using the 'pairs' function. For example:

<code>
for k, v in pairs (t) do
  f (k, v)
end 
</code>


name: table.getn
prototype: n = table.getn (t)
summary: Returns the size of a numerically-keyed table
doc_name: lua_tables
description:
Returns the size of the table using the rules described at the start of this page.

A table's size (which is only relevant for "numeric" indexed tables) is one less than the first integer index with a nil value. If the table has "holes" in it - that is, numeric keys with gaps in the sequence - then the table size is not guaranteed to be the the last gap. Lua does a binary search to try to find a gap, it does not necessarily find the first or last one.

<code>
table.getn { "the", "quick", "brown", "fox", name = "Nick" } --&gt; 4
</code>

Note that the length here is 4 and not 5, because the non-numeric entry (name = "Nick") is not considered to be part of the table's "length".

You can also use #t to find the length of a table.

<code>
# { "the", "quick", "brown", "fox", name = "Nick" } --&gt; 4
</code>

Contrast to table.maxn which finds the highest key by a linear scan (and is therefore slower).


name: table.insert
prototype: table.insert (t, pos, value)
summary: Inserts a new item into a numerically-keyed table
doc_name: lua_tables
description:
Inserts the value at (optional) position 'pos', renumbering existing elements if necessary to make room. Thus the new element becomes the one with index 'pos'.

If called with 2 arguments, the value is inserted at n+1, that is, the end of the table.

<code>
t = { "the", "quick", "brown", "fox" }
table.insert (t, 2, "very") -- new element 2
table.insert (t, "jumped")  -- add to end of table
table.foreachi (t, print)

 --&gt;

1 the
2 very
3 quick
4 brown
5 fox
6 jumped
</code>

The Lua authors recommend using the idiom "#t + 1" to insert to the end of a table nowadays. For example:

<code>
t = {}
t [#t + 1] = "hello, "
t [#t + 1] = "world"
</code>

Note that for other keys (eg. strings) you simply assign to the table item to insert it. For example:

<code>
t = {}
t.foo = "bar"    -- insert key "foo"
t ["Nick Gammon"] = 42  -- insert key "Nick Gammon"
</code>


name: table.maxn
prototype: n = table.maxn (t)
summary: Returns the highest numeric key in the table
doc_name: lua_tables
description:
Returns the highest numeric key in the table, by examining each entry in the entire table. This will necessarily be slower than doing table.getn, but would be needed if the keys have gaps in the sequence.

If the table does not have gaps in the keys, it is faster to use table.getn.


name: table.remove
prototype: val = table.remove (t, pos)
summary: Removes an item from a numerically-keyed table
doc_name: lua_tables
description:
Removes the element at position 'pos' from the table, returning the value of the removed element.

If 'pos' is omitted it defaults to the end of the table (n), thus removing the last element.


<code>
t = { "the", "quick", "brown", "fox" }
print (table.remove (t, 3))
table.foreachi (t, print)

 --&gt;
 
brown
1 the
2 quick
3 fox
</code>

The Lua authors recommend using this method for removing from the end of a table nowadays:

<code>
t [#t] = nil  -- remove last entry
</code>

Note that for other keys (eg. strings) you simply assign nil to the element to remove it. For example:

<code>
t = {}
t.foo = "bar"  -- add item
t.foo = nil    -- remove item
</code>


name: table.setn
prototype: table.setn (t, n)
summary: Sets the size of a table (obsolete)
doc_name: lua_tables
description:
This has been removed from Lua 5.1. Attempting to call it will raise an error. The length of a table can not be set, it is implied by the highest numeric key, providing there are no gaps in the sequence of numeric keys.


name: table.sort
prototype: table.sort (t, f)
summary: Sorts a table
doc_name: lua_tables
description:
Sorts the table using the supplied function f as the comparison function for each element.

Function f should return true if the first element is &lt; the second element. If the function omitted it defaults to the operator &lt;. 

Sorting is not stable, that is, the sequence of equal keys is not necessarily preserved.

<code>
t = { "the", "quick", "brown", "fox" }
table.sort (t)
table.foreachi (t, print)

 --&gt;
 
1 brown
2 fox
3 quick
4 the

</code>

Sorting is really only relevant for numerically keyed tables. If you want to sort the keys for other types of tables you need to make a copy of the keys and sort that, like this:

<code>
t = { str = 42, dex = 10, wis = 100 }
ts = {} -- table to hold the keys
table.foreach (t, function (k, v) table.insert (ts, k) end )
table.sort (ts) -- sort keys
table.foreachi (ts, print) -- print sorted keys

 --&gt;
 
1 dex
2 str
3 wis

</code>

Here is an example of a custom sort function. This is needed here because we are sorting tables, which do not have a natural "less than" operator:

<code>
t = {
    { str = 42, dex = 10, wis = 100 },
    { str = 18, dex = 30, wis = 5 }
    }

table.sort (t, function (k1, k2) return k1.str &lt; k2.str end )

table.foreachi (t, function (k, v) table.foreach (v, print) end )

 --&gt;
 
str 18
dex 30
wis 5
str 42
dex 10
wis 100

</code>

We can see from the results that the two tables were sorted into "str" order.

An alternative approach to supplying a comparison function for the sort would be to set up a metatable for the individual table items (not the container table) which specifies a __lt (less than) operator. Here is an example:

<code>
t = {
    { str = 42, dex = 10, wis = 100 },
    { str = 18, dex = 30, wis = 5 }
    }

mt =  { __lt = function (k1, k2) return k1.wis &lt; k2.wis end }

-- apply metatable to all tables inside our table
for _, v in ipairs (t) do
  setmetatable (v, mt)
end -- for

table.sort (t)

table.foreachi (t, function (k, v) table.foreach (v, print) end )

 --&gt;
 
str 18
dex 30
wis 5
str 42
dex 10
wis 100
</code>

In this case I have made a  metatable "mt" which is then applied to each table item. It compares the "wis" field in this case. With this in place the sort can be called without a helper function. Of course, for speed purposes you would do this once (perhaps when creating the individual table entries) rather than every time you wanted to sort it.


name: utils.functionlist
prototype: t = utils.functionlist ()
summary: Returns a table of MUSHclient world function names
doc_name: lua_utils
description:
This returns a table of all the internal MUSHclient function names (the same list used by the Help script function). 

The intention here is that you could use this table in an internal Notepad "global replace" to fix the capitalization of function names. You could also use it go generate keywords for use in text editors such as SciTE.

Example:

<code>
table.foreachi (utils.functionlist (), print)

--&gt;
1 Accelerator
2 AcceleratorList
3 Activate
4 ActivateClient
5 ActivateNotepad
6 AddAlias

...

296 WorldName
297 WorldPort
298 WriteLog
</code>


name: utils.filepicker
prototype: filename = utils.filepicker (title, name, extension, filter, save)
summary: Invokes the Windows standard "file picker" dialog box
doc_name: lua_utils
description:
This invokes the Windows standard "file picker" dialog box, which lets you choose a file for opening or saving. Usage is:

<code>
filter = { txt = "Text files", ["*"] = "All files" }

filename = utils.filepicker (title, name, extension, filter, save)
</code>

<ul>
<li/>title - title to appear on the dialog box (eg. "Name of plugin")
<li/>name  - default name of file to be loaded/saved
<li/>extension - default extension to use
<li/>filter - table of file filters, see example above
<li/>save - true for a "save" dialog, false for a "load" dialog
</ul>

All arguments are optional.

Returns nil if dialog dismissed, or the chosen filename if not.


name: utils.metaphone
prototype: m1, m2 = utils.metaphone (word)
summary: Returns metaphones (sound-alike codes) for the supplied word
doc_name: lua_utils
description:
This returns one or two metaphones (sound-alike codes) for the supplied word. This is the same behaviour as the world.Metaphone function, except that this one returns the secondary metaphone as a separate result.

eg.

<code>
print (utils.metaphone ("swordfish"))  --&gt; SRTF XRTF
</code>


name: utils.edit_distance
prototype: n = utils.edit_distance (word1, word2)
summary: Returns the Levenshtein Edit Distance between two words
doc_name: lua_utils
description:
This returns the Levenshtein Edit Distance between the two words. This is the same behaviour as the world.EditDistance function.

This could be used in a spell checker to work out how close a misspelt word is to a correctly spelt one.

eg.

<code>
print (utils.edit_distance ("food", "fodder"))  --&gt; 3
</code>


The Levenshtein distance between two strings  is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character.

For example, the Levenshtein distance between "kitten" and "sitting" is 3, since the following three edits change one into the other, and there is no way to do it with fewer than three edits:

<code>
   1. kitten --&gt; sitten (substitution of 's' for 'k')
   2. sitten --&gt; sittin (substitution of 'i' for 'e')
   3. sittin --&gt; sitting (insert 'g' at the end).
</code>


name: utils.spellcheckdialog
prototype: action, replacement = utils.spellcheckdialog (word, suggestions)
summary: Spell-checker dialog
doc_name: lua_utils
description:
This invokes a GUI dialog box, intended for use with a spell checker.

It is called with two arguments, the first being the misspelt word, the second being a table of suggested replacement words.

If this dialog is cancelled, utils.spellcheckdialog return nil.

Otherwise, it returns two things (which are strings): action, replacement

The action can be one of: 

<ul>
<li/>ignore
<li/>ignoreall
<li/>add
<li/>change
<li/>changeall
</ul>

The replacement is the replacement word - if the user chose "change" or "changeall" (or double-clicked a suggested word).

eg.

<code>
print (utils.spellcheckdialog ("fod", {"food", "fodder"} ))  --&gt; change food
</code>


name: utils.info
prototype: t = utils.info ()
summary: Information about directories, locale, etc.
doc_name: lua_utils
description:
This returns a table with the following things in it:

<ul>
<li/>"current_directory" --&gt; the current directory
<li/>"app_directory" --&gt; the directory in which MUSHclient.exe resides
<li/>"world_files_directory" --&gt;> the default world files directory
<li/>"log_files_directory" --&gt; the default log files directory
<li/>"plugins_directory" --&gt; the default plugins directory
<li/>"startup_directory" --&gt; the MUSHclient startup directory
<li/>"locale" --&gt; current locale identifier (eg. EN)
<li/>"fixed_pitch_font" --&gt; font used for fixed-pitch dialogs
<li/>"fixed_pitch_font_size" --&gt; point size of font used for fixed-pitch dialogs
<li/>"translator_file" --&gt; file used for translating messages
</ul>

This function is primarily intended for situations where you do not have access to the world "Info" functions, such as in the spell-checker.


name: utils.utf8encode
prototype: s = utils.utf8encode (u1, u2, ...)
summary: Encodes a series of Unicode codes into a UTF-8 string
doc_name: lua_utils
description:
This encodes a series of Unicode codes into a UTF-8 string. You can supply any number of arguments, which must be numbers in the range 0 to 2147483647. Any argument can also be a numerically-keyed table, in which case each sequential item (in the range 1 .. n) is also processed. If you supply a table the keys must not have gaps, or any item after the gap will be ignored. By supplying a table you can conveniently supply a large number of codes to be converted.

The function returns a string which is the appropriate UTF-8 encoded string. It raises an error if the arguments cannot be converted to numbers, are out of range, or have decimal places (eg. 5.5).

eg.

<code>
print (utils.tohex (utils.utf8encode (5000)))  --&gt; E18E88
print (utils.tohex (utils.utf8encode (5000, 10000))) --&gt; E18E88E29C90
print (utils.tohex (utils.utf8encode ( { 5000, 10000 } ))) --&gt; E18E88E29C90
</code>


name: utils.utf8decode
prototype: t = utils.utf8decode(s)
summary: Encodes a series of Unicode codes into a UTF-8 string
doc_name: lua_utils
description:
This decodes a UTF-8 string into a table of Unicode numbers. 

The function returns a (numerically-keyed) table of numbers, one for each Unicode code point found in the UTF-8 string argument. If the string is found to not be valid UTF-8 it returns nil.

eg.

<code>
t = utils.utf8decode (utils.fromhex ("E18E88"))
print (t [1])  --&gt; 5000
</code>


name: utils.utf8valid
prototype: n, column = utils.utf8valid (s)
summary: Checks if a UTF-8 string is valid
doc_name: lua_utils
description:
This checks if a UTF-8 string is valid. 

This returns the length of the string (in Unicode characters) if the supplied string is valid UTF-8.

Otherwise it returns nil, and the column of the character in error (1-relative).

eg.

<code>
print (utils.utf8valid (utils.fromhex ("F5838894FCB5898588B4"))) --&gt; 2
print (utils.utf8valid (utils.fromhex ("f0f0f0"))) --&gt; nil 1
</code>


name: bc.version
prototype: bc.version
summary: Version
doc_name: lua_bc
description:
A string representing the current version of the bc library. eg.

<code>
"bc library for Lua 5.1 / Aug 2006 / based on GNU bc-1.06"
</code>


name: bc.pow
prototype: n = bc.pow (a, b)
summary: Power
doc_name: lua_bc
description:
Returns a to the power b. For example:

<code>
print (bc.number (2) ^ 100)  --&gt; 1267650600228229401496703205376
print (bc.pow (2, 100))      --&gt; 1267650600228229401496703205376
</code>


name: utils.utf8sub
prototype: s = utils.utf8sub (str, start, end)
summary: Returns a substring of a UTF-8 string
doc_name: lua_utils
description:
Returns a substring of the UTF-8 string, starting at index 'start' and ending at index 'end'. Both may be negative to indicate counting from the right. The end point is optional and defaults to -1, which is the entire rest of the string.

For strings where each character has a character code of &lt; 128, the behaviour is identical to string.sub:

<code>
utils.utf8sub ("ABCDEF", 2, 3)  --&gt; BC
utils.utf8sub ("ABCDEF", 3)     --&gt; CDEF
utils.utf8sub ("ABCDEF", -1)    --&gt; F
</code>

The above examples are straight "ASCII" strings (ie. each byte is &lt; 128), however the behaviour is different to string.sub with UTF-8 strings. For example:

<code>
utils.utf8sub (utils.fromhex ("C686C689C69C"), 1, 2)  --&gt; (hex) C686C689
utils.utf8sub (utils.fromhex ("C686C689C69C"), -1, -1)  --&gt; (hex) C69C
</code>

For Unicode characters (ie. whose character code is &gt;= 128 and &lt;= 255) then the function calculates the number of bytes that each "Unicode code point" will require, and count each one as a "column".

The supplied string must be valid UTF-8. If not, the function returns nil followed by the byte position in error.


name: utils.umsgbox
prototype: response = utils.umsgbox ( msg, title, type, icon, default )
summary: Display a message box and get a response (Unicode)
doc_name: lua_utils
description:
This lets you display a Windows message box (very similar to MsgBox in VBscript). The intention is to allow you to display (in a small dialog box), information of an urgent nature, or ask a yes/no type question.

The calling sequence is:

<code>
result = utils.msgbox ( msg, title, type, icon, default )
</code>

The only required argument is the message text itself, the others default to their first possible value. The first 4 arguments are string arguments, the last is a number.

<ul>

  <li/>msg = message to display (max 1000 characters) - in UTF-8 characters (Unicode)
  <li/>title = title of box - if nil, defaults to &quot;MUSHclient&quot; (max 100 characters) - in UTF-8 characters (Unicode)
  <li/>type = type of box (must be in lower case and exactly as shown here): 

<ul>
  <li/>&quot;ok&quot; - The message box contains one push button: OK. This is the default. 
  <li/>&quot;abortretryignore&quot; - The message box contains three push buttons: Abort, Retry, and Ignore. 
  <li/>&quot;okcancel&quot; - The message box contains two push buttons: OK and Cancel. 
  <li/>&quot;retrycancel&quot; - The message box contains two push buttons: Retry and Cancel. 
  <li/>&quot;yesno&quot; - The message box contains two push buttons: Yes and No. 
  <li/>&quot;yesnocancel&quot; - The message box contains three push buttons: Yes, No, and Cancel. 
</ul>
  <li/>icon = type of icon: 

<ul>
  <li/>&quot;!&quot; - An exclamation-point icon appears in the message box. This is the default.
  <li/>&quot;?&quot; - A question-mark icon appears in the message box.
  <li/>&quot;i&quot; - An icon consisting of a lowercase letter i in a circle appears in the message box.
  <li/>&quot;.&quot; - A stop-sign icon appears in the message box.
</ul>
  <li/>default = default button (1 - 3)

This sets the default button (the one with the focus) to be either button 1, 2 or 3. The default is the first button.
</ul>

Return value = (string) yes, no, ok, retry, ignore, cancel, abort

Example:

<code>
print (utils.umsgbox (&quot;You are being paged&quot;, &quot;Warning!&quot;, &quot;ok&quot;, &quot;!&quot;, 1)) --&gt; ok
print (utils.umsgbox (&quot;You are being paged&quot;)) --&gt; ok
print (utils.umsgbox (&quot;Go ahead?&quot;, &quot;Question&quot;, &quot;yesno&quot;, &quot;?&quot;)) --&gt; yes / no
</code>

See also utils.msgbox if you want to display a message in straight ASCII (not Unicode).


name: utils.directorypicker
prototype: directoryname = utils. directorypicker (title, initial)
summary: Invokes the Windows standard "directory picker" dialog box
doc_name: lua_utils
description:
This invokes the Windows standard "directory picker" dialog box, which lets you choose a directory. Usage is:

<code>
directoryname = utils. directorypicker (title, initial)
</code>

<ul>
<li/>title - title to appear on the dialog box (eg. "Directory for backups")
<li/>initial  - initial directory - if omitted the current directory is used
</ul>

All arguments are optional.

Returns nil if dialog dismissed, or the chosen directory if not.

The directory name returned will <b>not</b> have a trailing backslash.


name: utils.getfontfamilies
prototype: fonts = utils.getfontfamilies ()
summary: Returns all fonts available to Windows
doc_name: lua_utils
description:
This lets you find the names of all the fonts installed on your current system.

The intention here is for scripts to decide if a font is available, before setting the output or command window to use that font.

For example:

<code>
t = utils.getfontfamilies ()

for font in pairs (t) do
  print (font)
end 

--&gt; Output:

Lucida Console
Comic Sans MS
Georgia
Mangal
WST_Engl
Wingdings
Sylfaen
Franklin Gothic Medium
Courier
</code>


name: utils.fontpicker
prototype: wanted_font = utils.fontpicker (name, size, colour)
summary: Invokes the Windows standard "font picker" dialog box
doc_name: lua_utils
description:
This invokes the Windows standard "font picker" dialog box, which lets you choose a font from those installed on your system.

<code>
wanted_font = utils.fontpicker (name, size, colour)
</code>

<ul>
<li/>name - preferred name (eg. name of the currently-selected font)
<li/>size  - preferred size in points
<li/>colour - preferred colour as an RGB colour
</ul>

All arguments are optional.

Returns nil if dialog dismissed, or the chosen font details (see below) if not.

If not dismissed, the font details are returned as a table, with the following entries:

<ul>
<li/>name - chosen name (eg. "Comic Sans MS")
<li/>size  - size in points (eg. 12)
<li/>colour - colour as an RGB colour code  (eg. 0 for black)
<li/>charset - character set code
<li/>underline  - 1 if underline chosen, 0 if not
<li/>strikeout - 1 if strikeout chosen, 0 if not
<li/>italic  - 1 if italic chosen, 0 if not
<li/>bold - 1 if bold chosen, 0 if not
<li/> style - the style as a string (eg. "Bold Italic")
</ul>


name: lpeg.match
prototype: lpeg.match (pattern, subject [, init])
summary: Matches a pattern against a string
doc_name: lua_lpeg
description:
The matching function. It attempts to match the given pattern against the subject string. If the match succeeds, returns the index in the subject of the first character after the match, or the values of captured values (if the pattern captured any value).

An optional numeric argument init makes the match starts at that position in the subject string. As usual in Lua libraries, a negative value counts from the end.

Unlike typical pattern-matching functions, match works only in anchored mode; that is, it tries to match the pattern with a prefix of the given subject string (at position init), not with an arbitrary substring of the subject. So, if we want to find a pattern anywhere in a string, we must either write a loop in Lua or write a pattern that matches anywhere. This second approach is easy and quite efficient.


name: lpeg.P
prototype: lpeg.P (value)
summary: Converts a value into a pattern
doc_name: lua_lpeg
description:
Converts the given value into a proper pattern, according to the following rules:

If the argument is a pattern, it is returned unmodified.

If the argument is a string, it is translated to a pattern that matches literally the string.

eg.

lpeg.P ("You gain")   --> matches "You gain"

If the argument is a non-negative number n, the result is a pattern that matches exactly n characters.

eg.

lpeg.P (5)   --> matches 5 characters

If the argument is a negative number -n, the result is a pattern that succeeds only if the input string does not have n characters: It is equivalent to the unary minus operation applied over the pattern corresponding to the (non-negative) value n.

eg.

lpeg.P (-2)   --> matches if there are not 2 more characters

lpeg.P (-1)   --> matches if there are no more characters (ie. the end of the string)

If the argument is a boolean, the result is a pattern that always succeeds or always fails (according to the boolean value), without consuming any input.

eg.

lpeg.P (true)   --> matches always
lpeg.P (false)   --> matches never

If the argument is a function, returns a pattern equivalent to a match-time capture over the empty string.

If the argument is a table, it is interpreted as a grammar (see below).


-- Grammars --

With the use of Lua variables, it is possible to define patterns incrementally, with each new pattern using previously defined ones. However, this technique does not allow the definition of recursive patterns. For recursive patterns, we need real grammars.

LPeg represents grammars with tables, where each entry is a rule.

The call lpeg.V(v) creates a pattern that represents the nonterminal (or variable) with index v in a grammar. Because the grammar still does not exist when this function is evaluated, the result is an open reference to the respective rule.

A table is fixed when it is converted to a pattern (either by calling lpeg.P or by using it wherein a pattern is expected). Then every open reference created by lpeg.V(v) is corrected to refer to the rule indexed by v in the table.

When a table is fixed, the result is a pattern that matches its initial rule. The entry with index 1 in the table defines its initial rule. If that entry is a string, it is assumed to be the name of the initial rule. Otherwise, LPeg assumes that the entry 1 itself is the initial rule.

As an example, the following grammar matches strings of a's and b's that have the same number of a's and b's:

equalcount = lpeg.P{
  "S";   -- initial rule name
  S = "a" * lpeg.V"B" + "b" * lpeg.V"A" + "",
  A = "a" * lpeg.V"S" + "b" * lpeg.V"A" * lpeg.V"A",
  B = "b" * lpeg.V"S" + "a" * lpeg.V"B" * lpeg.V"B",
} * -1


name: lpeg.R
prototype: lpeg.R ({range})
summary: Returns a pattern that matches a range of characters
doc_name: lua_lpeg
description:
Returns a pattern that matches any single character belonging to one of the given ranges. Each range is a string xy of length 2, representing all characters with code between the codes of x and y (both inclusive).

As an example, the pattern lpeg.R("09") matches any digit, and lpeg.R("az", "AZ") matches any ASCII letter.


name: lpeg.S
prototype: lpeg.S (string)
summary: Returns a pattern that matches a set of characters
doc_name: lua_lpeg
description:
Returns a pattern that matches any single character that appears in the given string. (The S stands for Set.)

As an example, the pattern lpeg.S("+-*/") matches any arithmetic operator.

Note that, if the argument is a single character (that is, a string of length 1), then lpeg.P(s) is equivalent to lpeg.S(s) which is equivalent to lpeg.R(s..s). Note also that both lpeg.S("") and lpeg.R() are patterns that always fail.


name: lpeg.V
prototype: lpeg.V (v)
summary: Creates a non-terminal variable for a grammar
doc_name: lua_lpeg
description:
This operation creates a non-terminal (a variable) for a grammar. The created non-terminal refers to the rule indexed by v in the enclosing grammar. 

The call lpeg.V(v) creates a pattern that represents the nonterminal (or variable) with index v in a grammar. Because the grammar still does not exist when this function is evaluated, the result is an open reference to the respective rule.

A table is *fixed* when it is converted to a pattern (either by calling lpeg.P or by using it wherein a pattern is expected). Then every open reference created by lpeg.V(v) is corrected to refer to the rule indexed by v in the table.

For example:

-- Grammar
local Exp, Term, Factor = lpeg.V"Exp", lpeg.V"Term", lpeg.V"Factor"
G = lpeg.P{ Exp,
  Exp = lpeg.Ct(Factor * (FactorOp * Factor)^0);
  Factor = lpeg.Ct(Term * (TermOp * Term)^0);
  Term = Number + Open * Exp * Close;
}


name: lpeg.locale
prototype: lpeg.locale ([table])
summary: Returns a table of patterns matching the current locale
doc_name: lua_lpeg
description:
Returns a table with patterns for matching some character classes according to the current locale. The table has fields named alnum, alpha, cntrl, digit, graph, lower, print, punct, space, upper, and xdigit, each one containing a correspondent pattern. Each pattern matches any single character that belongs to its class.

If called with an argument table, then it creates those fields inside the given table and returns that table.

For example:

local t = lpeg.locale()

function atwordboundary (p)
  return lpeg.P{
    [1] = p + t.alpha^0 * (1 - t.alpha)^1 * lpeg.V(1)
  }
end


name: lpeg.C
prototype: lpeg.C (patt)
summary: Creates a simple capture
doc_name: lua_lpeg
description:
Creates a simple capture, which captures the substring of the subject that matches patt. The captured value is a string. If patt has other captures, their values are returned after this one.

For example:

digits = lpeg.R ("09")
hp = lpeg.P ("You gain ") * lpeg.C (digits^1) * " hp."
print (lpeg.match (hp, "You gain 300 hp."))  --> 300


name: lpeg.Carg
prototype: lpeg.Carg (n)
summary: Creates an argument capture
doc_name: lua_lpeg
description:
Creates an argument capture. This pattern matches the empty string and produces the value given as the nth extra argument given in the call to lpeg.match.


name: lpeg.Cb
prototype: lpeg.Cb (name)
summary: Creates a back capture
doc_name: lua_lpeg
description:
This pattern matches the empty string and produces the values produced by the most recent group capture named name.

Most recent means the last complete outermost group capture with the given name. A Complete capture means that the entire pattern corresponding to the capture has matched. An Outermost capture means that the capture is not inside another complete capture.

For example:

open = "[" * lpeg.Cg(lpeg.P"="^0, "init") * "[" * lpeg.P"\n"^-1
close = "]" * lpeg.C(lpeg.P"="^0) * "]"
closeeq = lpeg.Cmt(close * lpeg.Cb("init"), function (s, i, a, b) return a == b end)
string = open * m.C((lpeg.P(1) - closeeq)^0) * close /
  function (o, s) return s end

The open pattern matches [=*[, capturing the repetitions of equal signs in a group named init; it also discharges an optional newline, if present. The close pattern matches ]=*]. The closeeq pattern first matches close; then it uses a back capture to recover the capture made by the previous open, which is named init; finally it uses a match-time capture to check whether both captures are equal. The string pattern starts with an open, then it goes as far as possible until matching closeeq, and then matches the final close. The final function capture simply consumes the captures made by open and close and returns only the middle capture, which is the string contents.


name: lpeg.Cc
prototype: lpeg.Cc ({value})
summary: Creates a constant capture
doc_name: lua_lpeg
description:
This pattern matches the empty string and produces all given values as its captured values.

digits = lpeg.R ("09")
hp = lpeg.P ("You gain ") * lpeg.C (digits^1) * " hp." * lpeg.Cc ("life")
print (lpeg.match (hp, "You gain 300 hp."))  --> 300 life


name: lpeg.Cf
prototype: lpeg.Cf (patt, func)
summary: Creates a fold capture
doc_name: lua_lpeg
description:
If patt produces a list of captures C1 C2 ... Cn, this capture will produce the value func(...func(func(C1, C2), C3)..., Cn), that is, it will fold (or accumulate, or reduce) the captures from patt using function func.

This capture assumes that patt should produce at least one capture with at least one value (of any type), which becomes the initial value of an accumulator. (If you need a specific initial value, you may prefix a constant capture to patt.) For each subsequent capture LPeg calls func with this accumulator as the first argument and all values produced by the capture as extra arguments; the value returned by this call becomes the new value for the accumulator. The final value of the accumulator becomes the captured value.

As an example, the following pattern matches a list of numbers separated by commas and returns their addition:

-- matches a numeral and captures its value
number = lpeg.R"09"^1 / tonumber

-- matches a list of numbers, captures their values
list = number * ("," * number)^0

-- auxiliary function to add two numbers
function add (acc, newvalue) return acc + newvalue end

-- folds the list of numbers adding them
sum = lpeg.Cf(list, add)

-- example of use
print(sum:match("10,30,43"))   --> 83


name: lpeg.Cg
prototype: lpeg.Cg (patt [, name])
summary: Creates a group capture
doc_name: lua_lpeg
description:
It groups all values returned by patt into a single capture. The group may be anonymous (if no name is given) or named with the given name.

An anonymous group serves to join values from several captures into a single capture. A named group has a different behavior. In most situations, a named group returns no values at all. Its values are only relevant for a following back capture or when used inside a table capture.

This example parses a list of name-value pairs and returns a table with those pairs:

lpeg.locale(lpeg)

local space = lpeg.space^0
local name = lpeg.C(lpeg.alpha^1) * space
local sep = lpeg.S(",;") * space
local pair = lpeg.Cg(name * "=" * space * name) * sep^-1
local list = lpeg.Cf(lpeg.Ct("") * pair^0, rawset)
t = list:match("a=b, c = hi; next = pi")  --> { a = "b", c = "hi", next = "pi" }

Each pair has the format name = name followed by an optional separator (a comma or a semicolon). The pair pattern encloses the pair in a group pattern, so that the names become the values of a single capture. The list pattern then folds these captures. It starts with an empty table, created by a table capture matching an empty string; then for each capture (a pair of names) it applies rawset over the accumulator (the table) and the capture values (the pair of names). rawset returns the table itself, so the accumulator is always the table.


name: lpeg.Cp
prototype: lpeg.Cp ()
summary: Creates a position capture
doc_name: lua_lpeg
description:
It matches the empty string and captures the position in the subject where the match occurs. The captured value is a number.


name: lpeg.Cs
prototype: lpeg.Cs (patt)
summary: Creates a substitution capture
doc_name: lua_lpeg
description:
Creates a substitution capture, which captures the substring of the subject that matches patt, with substitutions. For any capture inside patt with a value, the substring that matched the capture is replaced by the capture value (which should be a string). The final captured value is the string resulting from all replacements.

This example does a job somewhat similar to string.gsub. It receives a pattern and a replacement value, and substitutes the replacement value for all occurrences of the pattern in a given string:

function gsub (s, patt, repl)
  patt = lpeg.P(patt)
  patt = lpeg.Cs((patt / repl + 1)^0)
  return lpeg.match(patt, s)
end

As in string.gsub, the replacement value can be a string, a function, or a table.


name: lpeg.Ct
prototype: lpeg.Ct (patt)
summary: Creates a table capture
doc_name: lua_lpeg
description:
This capture creates a table and puts all values from all anonymous captures made by patt inside this table in successive integer keys, starting at 1. Moreover, for each named capture group created by patt, the first value of the group is put into the table with the group name as its key. The captured value is only the table.

The following code splits a string using a given pattern sep as a separator:

If the split results in too many values, it may overflow the maximum number of values that can be returned by a Lua function. In this case, we should collect these values in a table:

function split (s, sep)
  sep = lpeg.P(sep)
  local elem = lpeg.C((1 - sep)^0)
  local p = lpeg.Ct(elem * (sep * elem)^0)   -- make a table capture
  return lpeg.match(p, s)
end


name: lpeg.Cmt
prototype: lpeg.Cmt(patt, function)
summary: Creates a match-time capture
doc_name: lua_lpeg
description:
Unlike all other captures, this one is evaluated immediately when a match occurs. It forces the immediate evaluation of all its nested captures and then calls function.

The function gets as arguments the entire subject, the current position (after the match of patt), plus any capture values produced by patt.

The first value returned by function defines how the match happens. If the call returns a number, the match succeeds and the returned number becomes the new current position. (Assuming a subject s and current position i, the returned number must be in the range [i, len(s) + 1].) If the call returns false, nil, or no value, the match fails.

Any extra values returned by the function become the values produced by the capture.

For example:

A long string in Lua starts with the pattern [=*[ and ends at the first occurrence of ]=*] with exactly the same number of equal signs. If the opening brackets are followed by a newline, this newline is discharged (that is, it is not part of the string).

To match a long string in Lua, the pattern must capture the first repetition of equal signs and then, whenever it finds a candidate for closing the string, check whether it has the same number of equal signs.

<code>
equals = lpeg.P"="^0
open = "[" * lpeg.Cg(equals, "init") * "[" * lpeg.P"\n"^-1
close = "]" * lpeg.C(equals) * "]"
closeeq = lpeg.Cmt(close * lpeg.Cb("init"), function (s, i, a, b) return a == b end)
string = open * lpeg.C((lpeg.P(1) - closeeq)^0) * close / 1

print (string:match ("[===[ foo [=[ bar]=]  ]===]"))  -- test
</code>


The open pattern matches [=*[, capturing the repetitions of equal signs in a group named init; it also discharges an optional newline, if present. The close pattern matches ]=*], also capturing the repetitions of equal signs. The closeeq pattern first matches close; then it uses a back capture to recover the capture made by the previous open, which is named init; finally it uses a match-time capture to check whether both captures are equal. The string pattern starts with an open, then it goes as far as possible until matching closeeq, and then matches the final close. The final numbered capture simply discards the capture made by close.


name: lpeg.print
prototype: lpeg.print (pattern)
summary: Outputs debugging information to stdout
doc_name: lua_lpeg
description:
Sends debugging information to stdout.

This is not particularly easy to capture in a GUI application. To see it you could execute MUSHclient from the command line, like this:

mushclient.exe > lpeg_output.txt

Then inside MUSHclient use lpeg.print to print a pattern. Close MUSHclient and the file lpeg_output.txt should contain the debugging information.

For example:

00: char 'a'-> FAIL
01: set [(61-7a)]-> FAIL
10: end


name: sqlite3.open
prototype: sqlite3.open(filename)
summary: Opens or creates a database
doc_name: lua_sqlite3
description:
Opens (or creates if it does not exist) an SQLite database with name filename and returns its handle as userdata (the returned object should be used for all further method calls in connection with this specific database, see db:xxx methods). Example:

        myDB=sqlite3.open('MyDatabase.sqlite3')  -- open
        -- do some database calls...
        myDB:close()  -- close

In case of an error, the function returns nil, an error code and an error message.


name: sqlite3.open_memory
prototype: sqlite3.open_memory()
summary: Opens a database in memory
doc_name: lua_sqlite3
description:
Opens an SQLite database in memory and returns its handle as userdata. In case of an error, the function returns nil, an error code and an error message. (In-memory databases are volatile as they are never stored on disk.)


name: db:busy_handler
prototype: db:busy_handler([func[,udata]])
summary: Sets or removes a busy handler for a database
doc_name: lua_sqlite3
description:
Sets or removes a busy handler for a database. func is either a Lua function that implements the busy handler or nil to remove a previously set handler. This function returns nothing.

The handler function is called with two parameters: udata and the number of (re-)tries for a pending transaction. It should return nil, false or 0 if the transaction is to be aborted. All other values will result in another attempt to perform the transaction. (See the SQLite documentation for important hints about writing busy handlers.)


name: db:busy_timeout
prototype: db:busy_timeout(t)
summary: Sets a busy handler
doc_name: lua_sqlite3
description:
Sets a busy handler that waits for t milliseconds if a transaction cannot proceed. Calling this function will remove any busy handler set by db:busy_handler(); calling it with an argument less than or equal to 0 will turn off all busy handlers.


name: db:changes
prototype: db:changes()
summary: Returns number of changes by the most recent SQL statement
doc_name: lua_sqlite3
description:
This function returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement. Only changes that are directly specified by INSERT, UPDATE, or DELETE statements are counted. Auxiliary changes caused by triggers are not counted. Use db:total_changes() to find the total number of changes.


name: db:close
prototype: db:close()
summary: Closes a database
doc_name: lua_sqlite3
description:
Closes a database. All SQL statements prepared using db:prepare() should have been finalized before this function is called. The function returns sqlite3.OK on success or else a numerical error code (see the list of Numerical error and result codes).


name: db:close_vm
prototype: db:close_vm(temponly)
summary: Finalizes all statements that have not been explicitly finalized
doc_name: lua_sqlite3
description:
Finalizes all statements that have not been explicitly finalized. If temponly is true, only internal, temporary statements are finalized. This function returns nothing.


name: db:create_aggregate
prototype: db:create_aggregate(name,nargs,step,final)
summary: Creates an aggregate callback function
doc_name: lua_sqlite3
description:
This function creates an aggregate callback function. Aggregates perform an operation over all rows in a query. name is a string with the name of the aggregate function as given in an SQL statement; nargs is the number of arguments this call will provide. step is the actual Lua function that gets called once for every row; it should accept a function context (see below for callback contexts) plus the same number of parameters as given in nargs. final is a function that is called once after all rows have been processed; it receives one argument, the function context.

The function context can be used inside the two callback functions to communicate with SQLite3. Here is a simple example:

        db:exec[=[
          CREATE TABLE numbers(num1,num2);
          INSERT INTO numbers VALUES(1,11);
          INSERT INTO numbers VALUES(2,22);
          INSERT INTO numbers VALUES(3,33);
        ]=]
        local num_sum=0
        local function oneRow(context,num)  -- add one column in all rows
          num_sum=num_sum+num
        end
        local function afterLast(context)   -- return sum after last row has been processed
          context:result_number(num_sum)
          num_sum=0
        end
        db:create_aggregate("do_the_sums",1,oneRow,afterLast)
        for sum in db:urows('SELECT do_the_sums(num1) FROM numbers') do print("Sum of col 1:",sum) end
        for sum in db:urows('SELECT do_the_sums(num2) FROM numbers') do print("Sum of col 2:",sum) end

This prints:

        Sum of col 1:   6
        Sum of col 2:   66


CALLBACK CONTEXTS

A callback context is available as a parameter inside the callback functions db:create_aggregate() and db:create_function(). It can be used to get further information about the state of a query.

The various context functions are:

context:aggregate_count
context:get_aggregate_data
context:result
context:result_blob
context:result_error
context:result_int
context:result_null
context:result_number
context:result_text
context:set_aggregate_data
context:user_data


name: db:create_collation
prototype: db:create_collation(name,func)
summary: Creates a collation callback
doc_name: lua_sqlite3
description:
This creates a collation callback. A collation callback is used to establish a collation order, mostly for string comparisons and sorting purposes. name is a string with the name of the collation to be created; func is a function that accepts two string arguments, compares them and returns 0 if both strings are identical, -1 if the first argument is lower in the collation order than the second and 1 if the first argument is higher in the collation order than the second. A simple example:

        local function collate(s1,s2)
          s1=s1:lower()
          s2=s2:lower()
          if s1==s2 then return 0
          elseif s1&lt;s2 then return -1
          else return 1 end
        end
        db:exec[=[
          CREATE TABLE test(id INTEGER PRIMARY KEY,content COLLATE CINSENS);
          INSERT INTO test VALUES(NULL,'hello world');
          INSERT INTO test VALUES(NULL,'Buenos dias');
          INSERT INTO test VALUES(NULL,'HELLO WORLD');
        ]=]
        db:create_collation('CINSENS',collate)
        for row in db:nrows('SELECT * FROM test') do print(row.id,row.content) end


name: db:create_function
prototype: db:create_function(name,nargs,func)
summary: Creates a callback function
doc_name: lua_sqlite3
description:
This function creates a callback function. Callback function are called by SQLite3 once for every row in a query. name is a string with the name of the callback function as given in an SQL statement; nargs is the number of arguments this call will provide. func is the actual Lua function that gets called once for every row; it should accept a function context (see below for callback contexts) plus the same number of parameters as given in nargs. Here is an example:

        db:exec'CREATE TABLE test(col1,col2,col3)'
        db:exec'INSERT INTO test VALUES(1,2,4)'
        db:exec'INSERT INTO test VALUES(2,4,9)'
        db:exec'INSERT INTO test VALUES(3,6,16)'
        db:create_function('sum_cols',3,function(ctx,a,b,c)
          ctx:result_number(a+b+c)
        end))
        for col1,col2,col3,sum in db:urows('SELECT *,sum_cols(col1,col2,col3) FROM test') do
          print (string.format ('%2i+%2i+%2i=%2i\n',col1,col2,col3,sum))
        end

CALLBACK CONTEXTS

A callback context is available as a parameter inside the callback functions db:create_aggregate() and db:create_function(). It can be used to get further information about the state of a query.

The various context functions are:

context:aggregate_count
context:get_aggregate_data
context:result
context:result_blob
context:result_error
context:result_int
context:result_null
context:result_number
context:result_text
context:set_aggregate_data
context:user_data


name: db:errcode
prototype: db:errcode()
summary: Returns the most recent result code
doc_name: lua_sqlite3
description:
Returns the numerical result code (or extended result code) for the most recent failed call associated with database db. See Numerical error and result codes for details.


name: db:errmsg
prototype: db:errmsg()
summary: Returns the most recent error message
doc_name: lua_sqlite3
description:
Returns a string that contains an error message for the most recent failed call associated with database db.


name: db:exec
prototype: db:exec(sql[,func[,udata]])
summary: Executes SQL statements
doc_name: lua_sqlite3
description:
Compiles and executes the SQL statement(s) given in string sql. The statements are simply executed one after the other and not stored. The function returns sqlite3.OK on success or else a numerical error code (see Numerical error and result codes).

If one or more of the SQL statements are queries, then the callback function specified in func is invoked once for each row of the query result (if func is nil, no callback is invoked). The callback receives four arguments: udata (the third parameter of the db:exec() call), the number of columns in the row, a table with the column values and another table with the column names. The callback function should return 0. If the callback returns a non-zero value then the query is aborted, all subsequent SQL statements are skipped and db:exec() returns sqlite3.ABORT. Here is a simple example:

        sql=[=[
          CREATE TABLE numbers(num1,num2,str);
          INSERT INTO numbers VALUES(1,11,"ABC");
          INSERT INTO numbers VALUES(2,22,"DEF");
          INSERT INTO numbers VALUES(3,33,"UVW");
          INSERT INTO numbers VALUES(4,44,"XYZ");
          SELECT * FROM numbers;
        ]=]

        function showrow(udata,cols,values,names)
          assert(udata=='test_udata')
          print('exec:')
          for i=1,cols do print('',names[i],values[i]) end
          return 0
        end
        db:exec(sql,showrow,'test_udata')


name: db:interrupt
prototype: db:interrupt()
summary: Interrupts any pending operation
doc_name: lua_sqlite3
description:
This function causes any pending database operation to abort and return at the next opportunity. This function returns nothing.


name: db:last_insert_rowid
prototype: db:last_insert_rowid()
summary: Returns the key of the most recent insert into the database
doc_name: lua_sqlite3
description:
This function returns the rowid of the most recent INSERT into the database. If no inserts have ever occurred, 0 is returned. (Each row in an SQLite table has a unique 64-bit signed integer key called the 'rowid'. This id is always available as an undeclared column named ROWID, OID, or _ROWID_. If the table has a column of type INTEGER PRIMARY KEY then that column is another alias for the rowid.)

If an INSERT occurs within a trigger, then the rowid of the inserted row is returned as long as the trigger is running. Once the trigger terminates, the value returned reverts to the last value inserted before the trigger fired.

This returns a Lua number if possible, otherwise if the key is too large to be stored in a number it returns a string.


name: db:nrows
prototype: db:nrows(sql)
summary: Creates an iterator that returns a table of rows from a SELECT - keyed by name
doc_name: lua_sqlite3
description:
Creates an iterator that returns the successive rows selected by the SQL statement given in string sql. Each call to the iterator returns a table in which the named fields correspond to the columns in the database. Here is an example:

        db:exec[=[
          CREATE TABLE numbers(num1,num2);
          INSERT INTO numbers VALUES(1,11);
          INSERT INTO numbers VALUES(2,22);
          INSERT INTO numbers VALUES(3,33);
        ]=]
        for a in db:nrows('SELECT * FROM numbers') do table.print(a) end

This script prints:

        num2: 11
        num1: 1
        num2: 22
        num1: 2
        num2: 33
        num1: 3


Note: You should let the iterator finish (that is, get to the end of the selected rows) otherwise the database remains locked. So, do not "break" out of the for loop.


name: db:prepare
prototype: db:prepare(sql)
summary: Compiles an SQL statement
doc_name: lua_sqlite3
description:
This function compiles the SQL statement in string sql into an internal representation and returns this as userdata. The returned object should be used for all further method calls in connection with this specific SQL statement.

CALLBACK CONTEXTS

A callback context is available as a parameter inside the callback functions db:create_aggregate(),  db:create_function() and db:prepare(). It can be used to get further information about the state of a query.

The various context functions are:

context:aggregate_count
context:get_aggregate_data
context:result
context:result_blob
context:result_error
context:result_int
context:result_null
context:result_number
context:result_text
context:set_aggregate_data
context:user_data

<b>Example</b>

<code>
require "tprint"

-- make in-memory database
db = sqlite3.open_memory()

-- make a table for testing
db:exec  [[
          CREATE TABLE mobs (name, class, hp);
          INSERT INTO mobs VALUES("Naga", "mage", 666);
          INSERT INTO mobs VALUES("Wolf", "beast", 42);
          INSERT INTO mobs VALUES("Guard", "warrior", 100);
       ]]

-- prepare a SELECT statement
local stmt = db:prepare ("SELECT * FROM mobs")

-- loop until we get everything
while true do

  local result = stmt:step ()

  -- exit loop if done
  if result == sqlite3.DONE then
    break
  end -- if done

  -- should have ROW result
  assert (result == sqlite3.ROW, "Row not found")

  -- get all values into a table
  local row = stmt:get_named_values ()

  -- display them
  print (string.rep ("-", 20))
  tprint (row)
  
end -- while

-- done with this statement
stmt:finalize ()

-- finished with database
db:close ()
</code>


name: db:progress_handler
prototype: db:progress_handler(n,func,udata)
summary: Installs a progress callback function
doc_name: lua_sqlite3
description:
This function installs a callback function func that is invoked periodically during long-running calls to db:exec() or stmt:step(). The progress callback is invoked once for every n internal operations, where n is the first argument to this function. udata is passed to the progress callback function each time it is invoked. If a call to db:exec() or stmt:step() results in fewer than n operations being executed, then the progress callback is never invoked. Only a single progress callback function may be registered for each opened database and a call to this function will overwrite any previously set callback function. To remove the progress callback altogether, pass nil as the second argument.

If the progress callback returns a result other than 0, then the current query is immediately terminated, any database changes are rolled back and the containing db:exec() or stmt:step() call returns sqlite3.INTERRUPT. This feature can be used to cancel long-running queries.


name: db:rows
prototype: db:rows(sql)
summary: Creates an iterator that returns a table of rows from a SELECT - numerically keyed
doc_name: lua_sqlite3
description:
Creates an iterator that returns the successive rows selected by the SQL statement given in string sql. Each call to the iterator returns a table in which the numerical indices 1 to n correspond to the selected columns 1 to n in the database. Here is an example:

        db:exec[=[
          CREATE TABLE numbers(num1,num2);
          INSERT INTO numbers VALUES(1,11);
          INSERT INTO numbers VALUES(2,22);
          INSERT INTO numbers VALUES(3,33);
        ]=]
        for a in db:rows('SELECT * FROM numbers') do table.print(a) end

This script prints:

        1: 1
        2: 11
        1: 2
        2: 22
        1: 3
        2: 33



Note: You should let the iterator finish (that is, get to the end of the selected rows) otherwise the database remains locked. So, do not "break" out of the for loop.


name: db:total_changes
prototype: db:total_changes()
summary: Returns total number of changes
doc_name: lua_sqlite3
description:
This function returns the number of database rows that have been modified by INSERT, UPDATE or DELETE statements since the database was opened. This includes UPDATE, INSERT and DELETE statements executed as part of trigger programs. All changes are counted as soon as the statement that produces them is completed by calling either stmt:reset() or stmt:finalize().


name: db:trace
prototype: db:trace(func,udata)
summary: Installs debug trace callback
doc_name: lua_sqlite3
description:
This function installs a trace callback handler. func is a Lua function that is called by SQLite3 just before the evaluation of an SQL statement. This callback receives two arguments: the first is the udata argument used when the callback was installed; the second is a string with the SQL statement about to be executed.


name: db:urows
prototype: db:urows(sql)
summary: Creates an iterator that returns the rows from a SELECT
doc_name: lua_sqlite3
description:
Creates an iterator that returns the successive rows selected by the SQL statement given in string sql. Each call to the iterator returns the values that correspond to the columns in the currently selected row.

The difference between this and db:rows is that this function does not return a table, it returns the individual values as part of the function return value.

 Here is an example:

        db:exec[=[
          CREATE TABLE numbers(num1,num2);
          INSERT INTO numbers VALUES(1,11);
          INSERT INTO numbers VALUES(2,22);
          INSERT INTO numbers VALUES(3,33);
        ]=]
        for num1,num2 in db:urows('SELECT * FROM numbers') do print(num1,num2) end

This script prints:

        1       11
        2       22
        3       33


Note: You should let the iterator finish (that is, get to the end of the selected rows) otherwise the database remains locked. So, do not "break" out of the for loop.


name: stmt:bind
prototype: stmt:bind(n[,value])
summary: Binds a value to a parameter
doc_name: lua_sqlite3
description:
Binds value to statement parameter n. If the type of value is string or number, it is bound as text or double, respectively. If value is a boolean or nil or missing, any previous binding is removed. The function returns sqlite3.OK on success or else a numerical error code (see Numerical error and result codes).


name: stmt:bind_blob
prototype: stmt:bind_blob(n,blob)
summary: Binds a blob to a parameter
doc_name: lua_sqlite3
description:
Binds string blob (which can be a binary string) as a blob to statement parameter n. The function returns sqlite3.OK on success or else a numerical error code (see Numerical error and result codes).


name: stmt:bind_names
prototype: stmt:bind_names(nametable)
summary: Binds values in a table to parameters
doc_name: lua_sqlite3
description:
Binds the values in nametable to statement parameters. If the statement parameters are named (i.e., of the form ``:AAA'' or ``$AAA'') then this function looks for appropriately named fields in nametable; if the statement parameters are not named, it looks for numerical fields 1 to the number of statement parameters. The function returns sqlite3.OK on success or else a numerical error code (see Numerical error and result codes).


name: stmt:bind_parameter_count
prototype: stmt:bind_parameter_count()
summary: Returns the largest parameter index
doc_name: lua_sqlite3
description:
Returns the largest statement parameter index in prepared statement stmt. When the statement parameters are of the forms ``:AAA'' or ``?'', then they are assigned sequentially increasing numbers beginning with one, so the value returned is the number of parameters. However if the same statement parameter name is used multiple times, each occurrence is given the same number, so the value returned is the number of unique statement parameter names.

If statement parameters of the form ``?NNN'' are used (where NNN is an integer) then there might be gaps in the numbering and the value returned by this interface is the index of the statement parameter with the largest index value.


name: stmt:bind_parameter_name
prototype: stmt:bind_parameter_name(n)
summary: Returns the name of the n'th paremeter
doc_name: lua_sqlite3
description:
Returns the name of the n-th parameter in prepared statement stmt. Statement parameters of the form ``:AAA'' or ``@AAA'' or ``$VVV'' have a name which is the string ``:AAA'' or ``@AAA'' or ``$VVV''. In other words, the initial ``:'' or ``$'' or ``@'' is included as part of the name. Parameters of the form ``?'' or ``?NNN'' have no name. The first bound parameter has an index of 1. If the value n is out of range or if the n-th parameter is nameless, then nil is returned. The function returns sqlite3.OK on success or else a numerical error code (see Numerical error and result codes)


name: stmt:bind_values
prototype: stmt:bind_values(value1,value2,...,valueN)
summary: Binds values to parameters
doc_name: lua_sqlite3
description:
Binds the given values to statement parameters. The function returns sqlite3.OK on success or else a numerical error code (see Numerical error and result codes).


name: stmt:columns
prototype: stmt:columns()
summary: Returns number of columns in the result set
doc_name: lua_sqlite3
description:
Returns the number of columns in the result set returned by statement stmt or 0 if the statement does not return data (for example an UPDATE).


name: stmt:finalize
prototype: stmt:finalize()
summary: Frees a prepared statement
doc_name: lua_sqlite3
description:
This function frees prepared statement stmt. If the statement was executed successfully, or not executed at all, then sqlite3.OK is returned. If execution of the statement failed then an error code is returned.


name: stmt:get_name
prototype: stmt:get_name(n)
summary: Returns the name of a column in a result set
doc_name: lua_sqlite3
description:
Returns the name of column n in the result set of statement stmt. (The left-most column is number 0.)


name: stmt:get_named_values
prototype: stmt:get_named_values()
summary: Returns a table of names and values for the columns in a result set
doc_name: lua_sqlite3
description:
This function returns a table with names and values of all columns in the current result row of a query.


name: stmt:get_names
prototype: stmt:get_names()
summary: Returns a table of the names of all columns in a result set
doc_name: lua_sqlite3
description:
This function returns an array with the names of all columns in the result set returned by statement stmt.


name: stmt:get_type
prototype: stmt:get_type(n)
summary: Returns the type of a column in a result set
doc_name: lua_sqlite3
description:
Returns the type of column n in the result set of statement stmt. (The left-most column is number 0.)


name: stmt:get_types
prototype: stmt:get_types()
summary: Returns a table of the types of all columns in a result set
doc_name: lua_sqlite3
description:
This function returns an array with the types of all columns in the result set returned by statement stmt.


name: stmt:get_unames
prototype: stmt:get_unames()
summary: Returns a list of names of the columns in a result set
doc_name: lua_sqlite3
description:
This function returns a list with the names of all columns in the result set returned by statement stmt.


name: stmt:get_utypes
prototype: stmt:get_utypes()
summary: Returns a list of types of the columns in a result set
doc_name: lua_sqlite3
description:
This function returns a list with the types of all columns in the result set returned by statement stmt.


name: stmt:get_value
prototype: stmt:get_value(n)
summary: Returns the value of a column in a result set
doc_name: lua_sqlite3
description:
Returns the value of column n in the result set of statement stmt. (The left-most column is number 0.)


name: stmt:get_values
prototype: stmt:get_values()
summary: Returns a table of the values of all columns in a result set
doc_name: lua_sqlite3
description:
This function returns an array with the values of all columns in the result set returned by statement stmt.


name: stmt:nrows
prototype: stmt:nrows()
summary: Creates an iterator that returns a table of rows from a SELECT - keyed by name
doc_name: lua_sqlite3
description:
Returns an function that iterates over the names and values of the result set of statement stmt. Each iteration returns a table with the names and values for the current row. This is the prepared statement equivalent of db:nrows().


Note: You should let the iterator finish (that is, get to the end of the selected rows) otherwise the database remains locked. So, do not "break" out of the for loop.


name: stmt:reset
prototype: stmt:reset()
summary: Resets an SQL statement, so it can be executed again
doc_name: lua_sqlite3
description:
This function resets SQL statement stmt, so that it is ready to be re-executed. Any statement variables that had values bound to them using the stmt:bind*() functions retain their values.


name: stmt:rows
prototype: stmt:rows()
summary: Creates an iterator that returns a table of rows from a SELECT - numerically keyed
doc_name: lua_sqlite3
description:
Returns an function that iterates over the values of the result set of statement stmt. Each iteration returns an array with the values for the current row. This is the prepared statement equivalent of db:rows().


Note: You should let the iterator finish (that is, get to the end of the selected rows) otherwise the database remains locked. So, do not "break" out of the for loop.


name: stmt:step
prototype: stmt:step()
summary: Executes a previously-prepared SQL statement
doc_name: lua_sqlite3
description:
This function must be called to evaluate the (next iteration of the) prepared statement stmt. It will return one of the following values:

sqlite3.BUSY: the engine was unable to acquire the locks needed. If the statement is a COMMIT or occurs outside of an explicit transaction, then you can retry the statement. If the statement is not a COMMIT and occurs within a explicit transaction then you should rollback the transaction before continuing.

sqlite3.DONE: the statement has finished executing successfully. stmt:step() should not be called again on this statement without first calling stmt:reset() to reset the virtual machine back to the initial state.

sqlite3.ROW: this is returned each time a new row of data is ready for processing by the caller. The values may be accessed using the column access functions. stmt:step() can be called again to retrieve the next row of data.

sqlite3.ERROR: a run-time error (such as a constraint violation) has occurred. stmt:step() should not be called again. More information may be found by calling db:errmsg(). A more specific error code (can be obtained by calling stmt:reset().

sqlite3.MISUSE: the function was called inappropriately, perhaps because the statement has already been finalized or a previous call to stmt:step() has returned sqlite3.ERROR or sqlite3.DONE.


name: stmt:urows
prototype: stmt:urows()
summary: Creates an iterator that returns the rows from a SELECT
doc_name: lua_sqlite3
description:
Returns an function that iterates over the values of the result set of statement stmt. Each iteration returns the values for the current row. This is the prepared statement equivalent of db:urows().


Note: You should let the iterator finish (that is, get to the end of the selected rows) otherwise the database remains locked. So, do not "break" out of the for loop.


name: context:aggregate_count
prototype: context:aggregate_count()
summary: Returns the number of calls to the aggregate step function.
doc_name: lua_sqlite3
description:
A callback context is available as a parameter inside the callback functions db:create_aggregate() and db:create_function(). It can be used to get further information about the state of a query.


name: context:result
prototype: context:result(res)
summary: This function sets the result of a callback function to res.
doc_name: lua_sqlite3
description:
A callback context is available as a parameter inside the callback functions db:create_aggregate() and db:create_function(). It can be used to get further information about the state of a query.

        
The type of the result depends on the type of res and is either a number or a string or nil. All other values will raise an error message.


name: context:result_null
prototype: context:result_null()
summary: This function sets the result of a callback function to nil.
doc_name: lua_sqlite3
description:
A callback context is available as a parameter inside the callback functions db:create_aggregate() and db:create_function(). It can be used to get further information about the state of a query.

It returns nothing.


name: context:user_data
prototype: context:user_data()
summary: Returns the userdata parameter given in the call to install the callback function.
doc_name: lua_sqlite3
description:
A callback context is available as a parameter inside the callback functions db:create_aggregate() and db:create_function(). It can be used to get further information about the state of a query.

Returns the userdata parameter given in the call to install the callback function (see db:create_aggregate() and db:create_function() for details).


name: utils.callbackslist
prototype: t = utils.callbackslist ()
summary: Returns a table of plugin callback function names
doc_name: lua_utils
description:
This returns a table of all the internal plugin callback function names.

This could be used to detect whether or not a particular callback was available in this version of MUSHclient.

Example:

<code>
table.foreachi (utils.callbackslist (), print)

--&gt;
1 OnPluginBroadcast
2 OnPluginChatAccept
3 OnPluginChatDisplay
4 OnPluginChatMessage
5 OnPluginChatMessageOut
6 OnPluginChatNewUser
7 OnPluginChatUserDisconnect
8 OnPluginClose
9 OnPluginCommand
10 OnPluginCommandChanged
11 OnPluginCommandEntered
12 OnPluginConnect

...

41 OnPluginTick
42 OnPluginTrace
43 OnPluginWorldOutputResized
44 OnPluginWorldSave
</code>


name: utils.activatenotepad
prototype: utils.activatenotepad (title)
summary: Actvitates the specified notepad window
doc_name: lua_utils
description:
Activates the nominated notepad window, which does not belong to any world.

This is intended to be used for debugging or displaying information (eg. during development of localization scripts) in a notepad window, which is not related to any particular world.


eg.

utils.activatenotepad ("Debugging")



Returns true if successful, false if unsuccessful. (It would be false if the notepad did not exist).


name: utils.appendtonotepad
prototype: utils.appendtonotepad (title, message, replace)
summary: Appends text to the specified notepad window
doc_name: lua_utils
description:
Appends text to the nominated notepad window, which does not belong to any world.

This is intended to be used for debugging or displaying information (eg. during development of localization scripts) in a notepad window, which is not related to any particular world.


eg.

utils.appendtonotepad ("Debugging", "Loaded 10 files", false)


Returns true if successful, false if unsuccessful.


name: utils.sendtofront
prototype: found = utils.sendtofront (name)
summary: Bring a window to the front
doc_name: lua_utils
description:
Brings a nominated Windows window to the front - that is, it activates it.

This could be used to activate an editor, an email program, etc.

eg.

<code>
utils.sendtofront ("Crimson Editor")
</code>

It returns true if such a window exists, and false if not.

The name is case-sensitive, however only the first part matches (eg. the example above would match on "Crimson Editor - myfile.txt")


name: utils.shellexecute
prototype: ok, error = utils.shellexecute (filename, params, defdir, operation, show_command)
summary: Executes a Windows "shell" command
doc_name: lua_utils
description:
Only the first argument (filename) is required, the rest are optional.

<hr/>

<b>filename</b>:  The file to open or print or the folder to open or explore. 
  The function can open an executable file or a document file. 
  The function can print a document file. 

<b>params</b>:    A string that specifies the parameters to be passed to the application. 
  If filename specifies a document file, params should be nil or "".

<b>defdir</b>:    A string that specifies the default directory.
   
<b>operation</b>: The following operation strings are valid: 
 "open":  The function opens the file specified by the filename parameter. 
          The file can be an executable file or a document file. It can also be a folder. 
 "print": The function prints the file specified by filename. 
          The file should be a document file. 
          If the file is an executable file, the function opens the file, 
          as if "open" had been specified. 
 "explore":  The function explores the folder specified by filename.  

  This parameter can be nil or "". 
  In that case, the function opens the file specified by filename. 

<b>show_command</b>: If filename specifies an executable file, show_command specifies how the application is to be shown when it is opened. 

  This parameter can be nil in which case it defaults to 1 - the recommended default.
  
  This parameter can be one of the following values: 
  
   0:  Hides the window and activates another window. 
   1:  Activates and displays a window. 
       If the window is minimized or maximized, Windows restores it to 
       its original size and position. 
       An application should specify this flag when displaying the window for the first time. 
   2:  Activates the window and displays it as a minimized window. 
   3:  Activates the window and displays it as a maximized window. 
   4:  Displays a window in its most recent size and position. 
       The active window remains active. 
   5:  Activates the window and displays it in its current size and position.  
   6:  Minimizes the specified window and activates the next top-level window in the z-order. 
   7:  Displays the window as a minimized window. 
       The active window remains active. 
   8:  Displays the window in its current state. 
       The active window remains active. 
   9:  Activates and displays the window. 
       If the window is minimized or maximized, Windows restores it to its original 
       size and position. 
       An application should specify this flag when restoring a minimized window. 
  10:  Sets the show state based on the SW_ flag specified in the STARTUPINFO structure 
       passed to theCreateProcess function by the program that started the application. 
       An application should call ShowWindow with this flag to set the initial show 
       state of its main window. 
  
<hr/>

If sucessful, the function returns true. 

If not, it returns nil followed by an error message. You could use "assert" to test for failure.

<hr/>

Examples:

<code>
assert (utils.shellexecute ("c:/mushclient/worlds/SMAUG.MCL"))-- document
assert (utils.shellexecute ("http://www.gammon.com.au/"))     -- web page
assert (utils.shellexecute ("mailto:someone@somewhere.com"))  -- open mail client
assert (utils.shellexecute ("c:/", nil, nil, "explore"))      -- explore disk
assert (utils.shellexecute ("c:/readme.txt", nil, nil, "print"))  -- print a file
</code>

<b>Warning</b>: If you plan to redirect output (eg. capture a directory listing to a file) you may need to invoke the "cmd" shell. For example:

<code>
utils.shellexecute ("cmd", "/C dir &gt; test.txt", GetInfo (68))
</code>

You may also want to pass 0 as the fifth argument (hide the window) in order to stop a command window flickering into view and then disappearing, for example:

<code>
utils.shellexecute ("cmd", "/C dir &gt; test.txt", GetInfo (68), "open", 0)
</code>


name: utils.filterpicker
summary: Display a dialog box which filters its contents as you type
doc_name: lua_utils
prototype:
result = utils.filterpicker  (tbl, title, initial_filter, no_sort, filter_function, filter_prepare_function)

description:
This displays a dialog box with a predetermined list of items for the user to choose from, in the form of a multi-column table. If the user cancels the dialog box, or does not make a selection, nil is returned. Otherwise the key of the selected item is returned.

There is a "filter" box, which if you type into, reduces the visible contents of the dialog to whatever matches the filter (not case-sensitive). This could be used to reduce the displayed items to (for example) shops.

More examples, explanations, and screenshots are at:

http://mushclient.com/forum/?id=10618


The calling sequence is:

<code>
result = utils.filterpicker (t, title, initial_filter)
</code>

The only required arguments is the table of choices (t).

<ul>
  <li/>t - table of key/value pairs, as described below
  <li/>title = title of box - if nil, defaults to &quot;Filter&quot; (max 100 characters)
  <li/>initial_filter = initial filter value - defaults to no filter
  <li/>no_sort - if true, the list is not sorted alphabetically
  <li/>filter_function - optionally filter dynamically based on a function call.
  <li/>filter_prepare_function - function called each time something is typed into the filter box.
</ul>

Return value = the key of what they selected, or nil if cancelled, or nothing selected. 

The first argument is a table of key/value pairs. The value is displayed, however the corresponding key is returned. The values are automatically sorted into ascending alphabetic order.

The third argument is the initial value for the filter box. If empty, no filtering initially takes place.

The fourth argument suppresses sorting of the list, if true.

The fifth argument (filter_function) lets you decide at run-time via a function call whether or not to show each item.

This function is passed the current filter (what is wanted), the key of the item in question, and the value of the item in question.

So, for example, if you wanted the filter field to contain a number which indicated the length of words to be shown, you might write:

<code>
function filter_function (wanted, key, value)
  local length = tonumber (wanted)
  if not length then
     return false
  end -- if not number

  return #value == length
end -- filter
</code>

Every time the user types something into the "filter" box the filter function is called once for every item in the key/value table (to see if the item should be displayed).

The sixth argument (filter_prepare_function) lets you prepare for filtering. This is called once every time the user types something into the "filter" box. This could be used to do a FTS (full text search) of a database, based on the filter text, to find all matching rows. Then the filter function itself would simply see if a row had been found or not.

For example:

<code>
function filter_prepare_function (wanted)
  wanted_rooms = {}
  for row in db:nrows ("SELECT uid FROM rooms WHERE name MATCH '" .. wanted .. "'") do
    wanted_rooms [row.uid] = true
  end
end -- filter_prepare_function
</code>

<hr/>

Example of use:


<code>
print (utils.filterpicker ({ &quot;apples&quot;, &quot;bananas&quot;, &quot;peaches&quot;, &quot;cream&quot; }, &quot;Foods ...&quot; ))
</code>

Possible returned values would be:

<ul>
  <li/>nil - if no choice made or dialog cancelled
  <li/>1 - apples chosen
  <li/>2 - bananas chosen
  <li/>3 - peaches chosen
  <li/>4 - cream chosen
</ul>

(Note that peaches would actually be shown 4th in the list as the list is sorted).

To convert from the key back to the value, simply index into your table. Eg.

<hr/>

<code>
t = { &quot;apples&quot;, &quot;bananas&quot;, &quot;peaches&quot;, &quot;cream&quot; } 
result = utils.filterpicker (t, &quot;Foods ...&quot;)

if result then
  print (&quot;You chose&quot;, t [result])
else
  print &quot;Nothing chosen&quot;
end -- if
</code>

<hr/>

Keys and values can be either strings or numbers. MUSHclient will distinguish between strings and numbers which are the same (eg. &quot;10&quot; and 10 are considered different keys).

Here is an example of using string keys:


<hr/>
<code>
t = { 
    fruit = &quot;apple&quot;, 
    vegetable = &quot;potato&quot;, 
    spice = &quot;pepper&quot;, 
    herb = &quot;parsley&quot;,
    } 
result = utils.filterpicker (t, &quot;Foods ...&quot;)

if result then
  print (&quot;You chose key&quot;, result, &quot;which is&quot;, t [result])
else
  print &quot;Nothing chosen&quot;
end -- if
</code>
<hr/>


Possible returned values would be:

<ul>
  <li/>nil - if no choice made or dialog cancelled
  <li/>&quot;fruit&quot; - apple chosen
  <li/>&quot;vegetable&quot; - potato chosen
  <li/>&quot;spice&quot; - pepper chosen
  <li/>&quot;herb&quot;  - parsley chosen
</ul>


The return value will be one of the following types:


<ul>
  <li/>nil - if no selection made or dialog cancelled
  <li/>string - if an item with a string key is selected
  <li/>number - if an item with a numeric key is selected
</ul>


name: utils.timer
prototype: secs = utils.timer ( )
summary: Returns the high-resolution timer output
doc_name: lua_utils
description:
This returns the current output from the high-resolution timer (exactly the same as GetInfo (232) ). However this is easier to remember than GetInfo (232) every time you want to time some code.

If the high-performance timer is not available then the output from the lower-resolution timer is returned instead (seconds since midnight (00:00:00), January 1, 1970).

The intention of this is to allow you to time events, for example:

<code>
start = utils.timer ()

-- do stuff here

time_taken = utils.timer () - start
</code>


name: utils.infotypes
prototype: t = utils.infotypes ()
summary: Returns a table of all GetInfo type selectors
doc_name: lua_utils
description:
This returns a table with a description corresponding to each GetInfo selector.

For example:

<code>
print (utils.infotypes () [112], GetInfo (112))  --&gt; Automapper active false
</code>


name: lpeg.B
prototype: lpeg.B (patt, n)
summary: Matches patt n characters behind the current position, consuming no input
doc_name: lua_lpeg
description:
Returns a pattern that matches only if the input string matches patt starting n positions behind the current position. (The default value for n is 1.) If the current position is less than or equal to n, this pattern fails.

Like the "and predicate", this pattern never consumes any input, independently of success or failure, and it never produces any capture.

The pattern patt cannot contain any open reference to grammar rules (see grammars).

(This is an experimental feature. There is a good chance it will change in future versions.)


name: lpeg.setmaxstack
prototype: lpeg.setmaxstack (max)
summary: Sets the maximum size for the backtrack stack
doc_name: lua_lpeg
description:
Sets the maximum size for the backtrack stack used by LPeg to track calls and choices. Most well-written patterns need little backtrack levels and therefore you seldom need to change this maximum; but a few useful patterns may need more space. Before changing this maximum you should try to rewrite your pattern to avoid the need for extra space.


name: utils.reload_global_prefs
prototype: utils.reload_global_prefs ()
summary: Forces global preferences file to be reloaded
doc_name: lua_utils
description:
This forces the reload of the global preferences from the disk database. For example, after using the sqlite3 functions to modify one of them.


name: bit.clear
prototype: n = bit.clear (a, b, ...)
summary: Clears one or more bits
doc_name: lua_bit
description:
This takes one or more arguments. All are converted to signed 'long long' (64-bit integers). The result is the first argument 'and'ed with the ones-complement of the other arguments.

In other words, you can clear any bits in the first argument which are set in subsequent arguments.

eg.

<code>
a = bit.clear (0x111, 0x01)  --&gt; 0x110
a = bit.clear (0x111, 0x01, 0x10) --&gt; 0x100
</code>


Note that setting a bit can be simply done with bit.bor. 

Testing a bit can be done with bit.test.


name: bit.test
prototype: n = bit.test (a, b, ...)
summary: Bitwise 'test'
doc_name: lua_bit
description:
This takes one or more arguments. All are converted to signed 'long long' (64-bit integers). 

The second and subsequent arguments are or'ed together. The result is then and'ed with the first argument. The function returns true if the result of the 'and' is the value being 'and'ed with.

Effectively this tests whether or not various bits are set in the first argument.

The result is a boolean (true or false) and thus can be directly used in "if" tests.

eg.

<code>
print (bit.test (0x42, 0x02)) --&gt; true
print (bit.test (0x42, 0x40, 0x02)) --&gt; true
print (bit.test (0x02, 0x03)) --&gt; false (0x01 bit not set)
</code>

See also bit.band and bit.bor.

Note that setting a bit can be done with bit.bor. 
Clearing a bit can be done with bit.clear.


name: bc.powmod
prototype: n = bc.powmod (b, e, m)
summary: Raise to a power modulus another number
doc_name: lua_bc
description:
Returns b to the power e modulus m. For example:

<code>
print (bc.powmod (2, 9182347891540, 9182347891541))  --&gt; 7569093976632
</code>


name: bc.divmod
prototype: n = bc.divmod (a, b)
summary: Division and remainder
doc_name: lua_bc
description:
Returns a / b, and the remainder (a % b).

If b is zero, returns nil.

For example:

<code>
print (bc.divmod (7, 3))  --&gt;  2 1
</code>


name: bc.trunc
prototype: n = bc.trunc (a [, n ] )
summary: Truncate a number
doc_name: lua_bc
description:
Truncates a (gets rid of decimal places). If n is not specified, a is truncated to a whole number. Otherwise n is the number of decimal places wanted.

For example:

<code>
bc.digits (10)
print (bc.trunc (1234.567, 1))  --&gt;  1234.5
</code>


name: data types
prototype: Lua data types
summary: Types of data
doc_name: lua_syntax
description:
There are eight basic types in Lua: 

<ul>
<li/>nil
<li/>boolean
<li/>number
<li/>string
<li/>table

<li/>function

<li/>userdata
<li/>thread
</ul>

Note that values are typed, not variables. That is, a variable "foo" can contain any type of data, and that the type can change from moment to moment.

You can find the type of a value by using the "type" function, for example:

<code>print (type ("nick"))  --&gt; string</code>

The word returned by the "type" function will be one of the words in the list above.

<hr/>

<b>nil</b>

The value <b>nil</b> basically represents "no value". Global variables have the value nil by default, until something is assigned to them.

<hr/>

<b>boolean</b>

Boolean types only have two values, which are <b>true</b> and <b>false</b>.

Boolean types are usually used where you simply want to record if something is true or not.

However when doing condition tests (eg. an "if" statement) only two values are considered false:

<ul>
<li/>nil
<li/>false
</ul>

Every other value (including zero, and an empty string) are considered true.

<hr/>

<b>number</b>

The number type holds numbers (internally as the "double" floating point type). There is no integer type, as the double type can hold integers without rounding errors up to 100,000,000,000,000. *

In the case of MUSHclient, which is compiled with Microsoft Visual C++, the double type is documented to be in the range: 1.7E +/- 308 (15 digits)

Numeric constants can be written with optional signs, decimal points and exponents like this:

<code>42   -42.3   4.56e7   7.89e-10  0.3e12   22E+42</code>

Numeric constants can also be written in hexadecimal like this:

<code>0xA   0X0D   0x123456</code>

* See: http://en.wikipedia.org/wiki/Double_precision_floating-point_format

The mantissa of "double" numbers is 53 bits, giving it the ability to store a precision of almost 16 digits. (53 * math.log10(2) == 15.95 digits).


<hr/>

<b>string</b>

Strings are any sequence of characters, including none. Strings are "8-bit clean" which means you can store any character in them including 0x00. 

Literal strings are delimited by single or double quotes. The same quote that starts the string ends it, allowing you to use the other quote inside the string, eg.

<code>a = "Nick's cat"
b = 'Nick says "hello" to you'
</code>

Copying strings is fast as there is only ever one copy of the same string. Strings cannot be modified "in place". To change a string you always make a new copy.

If you attempt to do arithmetic on a string Lua will try to convert it to a number for you. For example:

<code>print("42" + 1)       --&gt; 43
print("1e5" * "1e2")  --&gt; 10000000</code>

However strings always compare unequal to numbers:

<code>print ("42" == 42)  --&gt; false</code>

See the entry for "string literals" for more details about strings.

<hr/>

<b>function</b>

Functions are "code that can be executed". They can be either written in Lua (by you) or C (the internal libraries). 

They are "first-class" values, that is they can be stored in variables, passed as arguments to other functions, and can be returned as the return value of another function. For example:

<code>
f = print    --  Assign the print function to the variable f
f ("hello")  --&gt; hello</code>

See the entry for "function" for more details about functions.

<hr/>

<b>table</b>

Tables implement associative arrays. That is, arrays of key/value pairs.

The keys and values can be any type, except nil.

The only way to create a table is by using a "table constructor" like this:

<code>my_table = { }</code>

The table constructor can also add initial key/value pairs to the table, eg.

<code>foods = {
   fish  = 10,
   chips = 11,
   cake  = 12
   }
</code>

In this example "fish" is a key, and the number 10 is the value associated with that key.

See the entry for "tables" for more details about tables.

<hr/>

<b>userdata</b>

The userdata type lets Lua store "C" data into a Lua variable. This is mainly used by libraries, for example to hold information about open files, regular expressions and so on.

<hr/>

<b>thread</b>

Threads are used for co-routines, which are independent units of execution which can yield execution to the caller and resume later.


name: precedence
prototype: Lua operator precedence
summary: Operator precedence
doc_name: lua_syntax
description:
Operator precedence specifies which operations are done first (for example, multiply before add).

You can use parentheses to change the precedence of an expression.

From highest to lowest the precedence is:


<code>
^
not #   - (unary)
*   /   %
+   -
..
&lt;   &gt;   &lt;=  &gt;=  ~=  ==
and
or
</code>

The # operator is the "length" operator which can be applied to things like strings and tables (eg. #"nick" is 4).

All binary operators are left-associative, except for "^" (exponentiation) and ".." (concatenation) which are right-associative.

What this means is that for left-associative operators at the same level (eg. + and -) they are grouped from left to right. Thus:

<code>a - b + c</code>

is the same as:

<code>(a - b) + c</code>

So for example:

<code>3 - 1 + 5  --&gt; 7 (not -3) </code>


However for concatenation:

<code>a .. b .. c</code>

is the same as:

<code>a .. (b .. c)</code>


And for exponentiation:

<code>a^b^c</code>

is the same as:

<code>a^(b^c)</code>

For example:

<code>print (4^3^2)  --&gt; 262144 (not 4096)</code>


name: assignment
prototype: Lua assignment
summary: Assignment
doc_name: lua_syntax
description:
Assignment lets you "assign" (set) a variable to a value.

eg.

<code>
a = 42
b = "hello"
</code>

You can do multiple assignments, eg.

<code>
a, b = 42, "hello"
</code>

That does the same thing as the first example.

Multiple assignments are not generally used on their own (they can be confusing to read), except in collecting the results from a function. Functions can return multiple results, so multiple assignment is a useful way of getting those results. eg.

<code>
a, b, c = string.find ("the quick brown fox", "(a+)")
</code>

In this example, a will get the start character position of the match, b will get the end position, and c will get the capture.

<hr/>

With multiple assignment, if you (or the function) provides too few values, the extra ones are set to nil, eg.

<code>
a, b, c, d = 0, 1
</code>

This sets a to 0, b to 1, and c and d are both set to nil.

<hr/>

If you provide too many values, the extra ones are silently discarded, eg.

<code>
a = 1, 2, 3, 4, 5, 6
</code>

The values 2, 3, 4, 5, 6 are just discarded.


name: local
prototype: Local variables
summary: Local variables
doc_name: lua_syntax
description:
Local variables are created with the <b>local</b> statement. Their scope is limited to the block where they are declared.

eg.

<code>
a = 1 -- global variable
local b = 2 -- local variable
</code>

Global variables are stored in the "global environment table" which is generally accessible to all functions. Local variables are only visible to the block in which they are "seen". For example:

<code>
function foo ()
  local x = 42  -- x is only visible inside foo
  y = 63  -- global variable y is changed
end -- function foo
</code>

In this example if there was another variable "x" somewhere else in the program, it would not be affected by the local variable x inside foo.

Be aware that if you redefine a local variable you get a new one of the same name. Eg.

<code>
function foo ()
  local x = 42  -- x is only visible inside foo
  
  -- do various things here

  local x = 43  -- this is a new variable x, we have not changed the earlier one
end -- function foo
</code>

If you want to change an existing local variable, do not use the word local again, eg.

<code>
function foo ()
  local x = 42  -- x is only visible inside foo
  
  -- do various things here

  x = 43  -- we have changed the earlier one
end -- function foo
</code>


name: if / then / else
prototype: Lua if
summary: If statements
doc_name: lua_syntax
description:
You can use <b>if</b> <i>condition</i> <b>then</b> ... <b>end</b> to test a condition and execute code conditionally, eg.

<code>if button_pressed then
  start_motor ()
end  -- if button pressed
</code>

If you want to do something else if the condition is not true you can use an <b>else</b> clause:

<code>if button_pressed then
  start_motor ()
else
  turn_on_lights ()
end  -- if
</code>

For multiple tests you can use <b>elseif</b> which avoids having to use <b>end</b> multiple times:

<code>if action == "heal" then
  heal_player ()
elseif action == "sleep" then
  goto_sleep ()
elseif action == "attack" then
  attack_mob ()
else
  print "invalid action"
end  -- if
</code>

The only conditions that are false are the values <b>false</b> and <b>nil</b> - every other value is considered true.

You can of course reverse a condition by using <b>not</b> like this:

<code>if not asleep then
  eat_food ()
end  -- if not asleep
</code>

<hr/>

It is considered good programming practice to indent the contents of an <b>if</b> statement, to make it clear what parts are being executed conditionally.

It is also a good idea to put a comment on the <b>end</b> indicating what it is the end of (as in the examples above). This is because the keyword <b>end</b> can end <b>if</b> statements, <b>while</b> statements, <b>for</b> statements, <b>do</b> statements, and <b>function</b> bodies.


name: while
prototype: Lua while
summary: Loop with test at start
doc_name: lua_syntax
description:
You can make code loop by using <b>while</b> <i>condition</i> <b>do</b> ... <b>end</b> - the test is done at the start of the loop, so if the test fails the loop may not be executed at all.

<code>while danger_threatens () do
  flash_lights ()
end  -- while
</code>

If you want to leave the loop from inside you can use a <b>break</b> statement:

<code>while danger_threatens () do
  flash_lights ()
  if enough_flashing () then
    break
  end -- if
end  -- while
</code>

The only conditions that are false are the values <b>false</b> and <b>nil</b> - every other value is considered true.

If you want to test at the end of the loop use <b>repeat</b> instead.


name: repeat
prototype: Lua repeat
summary: Loop with test at end
doc_name: lua_syntax
description:
You can make code loop by using <b>repeat</b> ... <b>until</b> <i>condition</i>  - the test is done at the end of the loop, so the body of the loop is always executed at least once.

<code>local action
repeat 
  action = get_action ()
until action ~= ""
</code>

If you want to leave the loop from inside you can use a <b>break</b> statement:

<code>local action
local count = 0
repeat 
  action = get_action ()

  count = count + 1
  if count > 5 then
    break
  end -- if

until action ~= ""
</code>


The only conditions that are false are the values <b>false</b> and <b>nil</b> - every other value is considered true.

If you want to test at the start of the loop use <b>while</b> instead.


name: for (numeric)
prototype: Lua for
summary: Loop with a range of numbers
doc_name: lua_syntax
description:
The numeric <b>for</b> lets you loop a specific number of times, eg.

<code>for var = start, finish, step do
  some_action ()
end 
</code>

The three expressions are evaluated once before the loop starts. "start" is the initial value, "finish" is the limit of the loop, and "step" is what to add after each iteration. For example:

<code>for i = 1, 10, 2 do
  print (i) --&gt; 1, 3, 5, 7, 9
end 

for i = 10, 1, -3 do
  print (i) --&gt; 10, 7, 4, 1
end 

for i = 1, 5 do
  print (i) --&gt; 1, 2, 3, 4, 5
end 
</code>

The "loop control" variable (i in the examples above) is only visible inside the loop. It is a mistake to try to access it outside the loop. If you must remember what the loop control variable was when exiting a loop, save it in another variable.

You should not attempt to <i>change</i> the loop control variable. Doing so will lead to undefined results. 

If you want to leave the loop from inside you can use a <b>break</b> statement.

<hr/>

More specifically what happens in the numeric "for" is:

<ul>
<li/>The three control expressions (start, finish, step) are evaluated once and stored into local variables (start variable, finish variable, step variable). These evaluations must result in numbers or an error is raised. If omitted, the step variable is assumed to be one.

<li/>The loop control variable (var) is set to the start variable.

<li/>If the step variable is positive, then the loop control variable is tested to see if it is less than, or equal to, the finish variable. If not, the loop exits.

<li/>If the step variable is negative or zero, then the loop control variable is tested to see if it is greater than, or equal to, the finish variable. If not, the loop exits.

<li/>The loop body is now executed.

<li/>The step variable is added to the loop control variable.

<li/>Control passes back to the start of the loop to test the loop control variable again.
</ul>


name: for (generic)
prototype: Lua generic for
summary: Loop using an iterator function
doc_name: lua_syntax
description:
The generic <b>for</b> lets you loop under the control of an iterator, eg.

<code>for key, value in pairs (my_table) do
  print (key, value)
end 
</code>

The keyword <b>in</b> distinguishes the "generic for" from the "numeric for".

The "generic for" requires three expressions after the word "in" (which might be supplied by a function call such as pairs or ipairs):

<ul>
<li/>An iterator function: "f"
<li/>A state value: "s"
<li/>An initial value of the iterator variable: "i"
</ul>

The equivalent of using pairs (my_table) is to do this:

<code>for key, value in next, my_table, nil do
  print (key, value)
end 
</code>

In this case "next" is the iterator function, my_table is the state value, and nil is the initial value to be passed to the iterator.

<hr/>

If you want to leave the loop from inside you can use a <b>break</b> statement.

You should not attempt to <i>change</i> the loop control variable (the first value returned). Doing so will lead to undefined results.

You don't normally need to be too concerned about the inner details of the "generic for". Often it is used to traverse tables by using the functions <b>pairs</b> or <b>ipairs</b> which return the correct iterators and initial values. For example:

<code>t = { "every", "good", "boy", "deserves", "fruit" }

for key, value in pairs (t) do
  print (key, value)
end -- for
</code>

Results:

<code>1 every
2 good
3 boy
4 deserves
5 fruit
</code>

<hr/>

More specifically what happens in the generic "for" is:

<ul>
<li/>The three expressions are evaluated once before the loop starts. The first argument must be a function (the iterator function).

<li/>The iterator function is called with both the state "s" and the iterator variable "i". 

The state might be a table we are traversing, and the iterator variable might be how far through that table we are. 

In effect:

<code>var1, var2, var3 = f (s, i)</code>

<li/>The first value returned by the iterator function becomes the iterator variable for the next round. 

<li/>If the first value returned by the iterator function is nil the loop terminates.

<li/>Otherwise the body of the loop executes and then the process (of calling the iterator function onwards) is repeated.

</ul>

The "next" function is an example of an iterator function. It takes a table and current key, and returns the key/value pair of the <i>next</i> entry. The current key can then be used to get the next one again, and so on. Since the "next" function returns the first key in the table if the "current key" is nil, then we initially start off with nil as the iterator variable.


name: break
prototype: Lua break
summary: Exit a loop early
doc_name: lua_syntax
description:
The <b>break</b> statement is used to terminate a loop (<b>while</b>, <b>repeat</b> or <b>for</b> loop) early.

For example:

<code>while true do
  if mob_in_room () then
    break
  end -- if
end -- while
</code>

Also see the <b>return</b> statement which is used to leave the current function (not just the current loop).


name: return
prototype: Lua return
summary: Exit from a function
doc_name: lua_syntax
description:
The return statement exits the current function, optionally returning values to the caller. For example:

<code>return   -- exit returning no values
return 1, 2, 3, 4  -- exit returning four values
</code>

Every function has an implicit <b>return</b> at the end of it, so you don't normally need to put your own, unless you want to return values.

Functions can return multiple values, which can be "captured" by a multiple assignment statement. For example:

<code>function foo ()
  return 1, 2, 3, 4
end -- function foo

a, b, c, d = foo ()  --&gt; assigns the values 1, 2, 3, 4
</code>

If a function returns a function call, then multiple values returned by the calling function are returned. For example:

<code>function foo ()
  return 1, 2, 3, 4
end -- function foo

function bar ()
  return foo ()
end -- function bar

print (bar ())  --&gt; 1, 2, 3, 4
</code>

If a function returns multiple values and those values are used in an expression list, then the multiple values are adjusted to one value (the first) unless they are used in the last or only place. For example:

<code>function foo ()
  return 1, 2, 3, 4
end -- function foo

print (foo (), 8)  --&gt; 1, 8 (other values discarded)
</code>

However:

<code>function foo ()
  return 1, 2, 3, 4
end -- function foo

print (8, foo ())  --&gt; 8, 1, 2, 3, 4 (all values retained)
</code>


name: do
prototype: Lua do
summary: Make a block
doc_name: lua_syntax
description:
You can use <b>do</b> ... <b>end</b> to make a "block". This can be useful if you want to have a local variable limited in scope, eg.

<code>do
  local foo = 22
  -- use foo here
end -- of do
</code>

Also you need to use "do ... end" if you want to put a return inside the middle of a function (eg. for testing), like this:

<code>do return end</code>


name: function
prototype: Lua functions
summary: Function declaration
doc_name: lua_syntax
description:
The <b>function</b> keyword declares a Lua function (functions can also be written in C).

Functions take zero or more arguments (which become local variables inside the function), like this:

<code>function foo (a, b, c)
  return a + b + c
end -- function foo
</code>

If you don't require arguments you still need the brackets:

<code>function foo ()
  print "hi there"
end -- function foo
</code>

If the caller does not supply all the argument values, the extra ones are set to <b>nil</b>.

Functions can also be declared in an assignment statement like this:

<code>foo = function (a, b, c)
  return a + b + c
end -- function
</code>

This is equivalent to the earlier example.

Functions can return multiple results (see the <b>return</b> statement for more details).

<hr/>

A special form of function argument is the "..." syntax which represents "a variable number of arguments". If used, it must be the last (or only) argument in the function argument list.

For example:

<code>function f (...)
  print (select ("#", ...))  --&gt; 4
  print (select (2, ...))    --&gt; 20  30  40
end -- function f

f (10, 20, 30, 40)
</code>

This is useful in cases where you want to pass an unknown number of arguments to a function. The <b>select</b> function is useful for extracting out the individual arguments. Also the <b>unpack</b> function can be used to turn the "..." argument into a table.

<hr/>

Functions are called by supplying the function name followed by the arguments (if any) in brackets. Even if there are no arguments you must use the brackets, otherwise you are just assigning the function. For example:

<code>a = f     -- variable a now contains function f
a = f ()  -- calls function f, puts first result (if any) into a   
</code>

There is an ambiguity in Lua because of the above, so Lua requires the opening bracket to be on the same line as the function. In other words, this is not permitted:

<code>print
 ("hello")</code>

However this is OK:

<code>print (
  "hello")</code>

<hr/>

Functions can be anonymous, that is, just used where a function is required without assigning them to any variable (and thus they don't have a name). For example, to sort some numbers into descending order:

<code>table.sort (  { 22, 33, 44, 66, 99 }, 
              function (k1, k2) return k2 &lt; k1 end )
for k, v in ipairs (t) do print (v) end</code>

Output:

<code>99
66
44
33
22</code>

In that example, an anonymous table was sorted using an anonymous comparison function.


name: keywords
prototype: Lua keywords
summary: Reserved words
doc_name: lua_syntax
description:
The following keywords are reserved by Lua and thus cannot be used for variable names:

<ul>
<li/>and
<li/>break
<li/>do
<li/>else
<li/>elseif
<li/>end
<li/>false
<li/>for
<li/>function
<li/>if
<li/>in
<li/>local
<li/>nil
<li/>not
<li/>or
<li/>repeat
<li/>return
<li/>then
<li/>true
<li/>until
<li/>while 
</ul>


name: identifiers
prototype: Lua identifiers
summary: Naming rules
doc_name: lua_syntax
description:
Identifiers in Lua can be any string of letters, digits, and underscores, not beginning with a digit, of any length. For example:

<code>a   b   monster    abc876    _foo   a_variable_with_a_long_name</code>

You should avoid using identifiers starting with an underscore <i>followed by upper-case letters</i>, as these are reserved for Lua variables such as _VERSION.

Lua is case-sensitive, so foo and FOO are different identifiers.

Identifiers cannot be reserved words, these words are reserved: 

<ul>
<li/>and
<li/>break
<li/>do
<li/>else
<li/>elseif
<li/>end
<li/>false
<li/>for
<li/>function
<li/>if
<li/>in
<li/>local
<li/>nil
<li/>not
<li/>or
<li/>repeat
<li/>return
<li/>then
<li/>true
<li/>until
<li/>while 
</ul>


name: comments
prototype: Lua comments
summary: How to make comments
doc_name: lua_syntax
description:
A single-line comments starts with "--" and ends at the end of the line, eg.

<code>a = 42 -- initial value of 'a'</code>

You can also use "block" comments by following the hyphens by brackets like this:

<code>--[[
  Written by Nick Gammon.
  Date: 3rd June 2011
]]
</code>

To allow for nesting block comments you can add in one or more "=" symbols like this:

<code>--[=[
  Written by Nick Gammon.
  Date: 3rd June 2011

  --[===[
    Nested comment.
  ]===]

  Not nested.
]=]
</code>


name: string literals
prototype: Lua string literals
summary: How to write constant strings
doc_name: lua_syntax
description:
Literal strings (constants) are delimited by single or double quotes. Square brackets can also be used, as described below.

The same quote that starts the string ends it, allowing you to use the other quote inside the string, eg.

<code>a = "Nick's cat"
b = 'Nick says "hello" to you'
</code>

You can also use certain "escape" sequences to imbed special characters:

<code>
\a	bell (0x07)
\b	backspace  (0x08)
\f	form feed (0x0C)
\n	newline  (0x0A)
\r	carriage return (0x0D)
\t	horizontal tab (0x09)
\v	vertical tab (0x0B)
\\	backslash
\"	double quote
\'	single quote
\[	left square bracket
\]	right square bracket
</code>

You can also imbed other codes by using \ddd where ddd is up to 3 decimal digits. For example:

<code>a = "\027"  -- the "escape" character (hex 0x1B)</code>

Be cautious if you do not use exactly three digits, because then another digit following the code might be considered to be part of it.

You can also use square brackets to make multiple-line strings, or strings with both sorts of quotes inside them. For example:

<code>a = [[
Here you will experience your first full combat against MOBILES, also known
as MOBS. Mobile is the name used for monsters and the like in the game.
All exits, except down, lead to a CAGE mob. Some of these cage mobs may be
aggressive and will attack you upon entering their room. As you kill them,
you will gain experience, as well as academy equipment and gold.
]]</code>

This sort of literal string <b>ignores escape sequences</b>. It also discards a newline if the first character is a newline (as in the example above).

If you might have two brackets inside the string you can use "=" signs to make strings which only match the same number of "=" signs at the end, for example:

<code>a = [====[
Here you will experience your first full combat against MOBILES, also known
as MOBS. Mobile is the name used for monsters and the like in the game.
All exits, except down, lead to a CAGE mob. Some of these cage mobs may be
aggressive and will attack you upon entering their room. As you kill them,
you will gain experience, as well as academy equipment and gold.
]====]</code>

Another way of doing multiple-line strings is to put a backslash at the end of the line, eg.

<code>a = "Here you will experience your first full combat against MOBILES, also known \
as MOBS. Mobile is the name used for monsters and the like in the game. \
All exits, except down, lead to a CAGE mob. Some of these cage mobs may be \
aggressive and will attack you upon entering their room. As you kill them, \
you will gain experience, as well as academy equipment and gold."</code>


name: relational operators
prototype: Lua relational operators
summary: Comparison
doc_name: lua_syntax
description:
Lua provides the following relational operators:

<code>    &lt;   &gt;   &lt;=  &gt;=  ==  ~=</code>

All these operators always result in <b>true</b> or <b>false</b>.

The operator == tests for equality; the operator ~= is the negation of equality. 

If the values are different types they are considered different values. For example, "5" (string type) is not the same as 5 (number type).

Tables, userdata and functions are compared by reference. That is they are considered equal only if they are the same underlying object. Thus two tables, which happen to contain the same things, but which were created separately, are considered different.

Note that the equality test is "==", not just "=". Thus this is <i>incorrect</i>:

<code>if a = 5 then  -- wrong! use a == 5 instead</code>

Also note that the inequality test is "~=", not "!=" as used by the C language.


name: logical operators
prototype: Lua logical operators
summary: Logical comparison
doc_name: lua_syntax
description:
The logical operators are <b>and</b>, <b>or</b>, and <b>not</b>. Like control structures, all logical operators consider <b>false</b> and <b>nil</b> as <b>false</b> and anything else (including zero) as <b>true</b>. The operator <b>and</b> returns its first argument if it is false; otherwise, it returns its second argument. The operator <b>or</b> returns its first argument if it is not false, otherwise, it returns its second argument.

Both <b>and</b> and <b>or</b> use short-cut evaluation, that is, they evaluate their second operand only when necessary. 

A useful technique is to use the ability of <b>or</b> to return its first argument if it is not false to quickly test if a variable exists. For example:

<code>t = t or {} -- create table if it does not exist</code>

The operator <b>not</b> always returns <b>true</b> or <b>false</b>.


name: tables
prototype: Lua tables
summary: Table data types
doc_name: lua_syntax
description:
Tables implement associative arrays. That is, arrays of key/value pairs.

The keys and values can be any type, except <b>nil</b>.

The only way to create a table is by using a "table constructor" like this:

<code>t = {}</code>

The table constructor can also add initial key/value pairs to the table, eg.

<code>foods = {
   fish  = 10,
   chips = 11,
   cake  = 12
   }
</code>

You can add elements later or in the constructor. Ultimately either method gives the same end result.

Once you have a table you can get at the values in it by "indexing" into the table. One way is this:

<code>print ( foods ["fish"] )  --&gt; 10</code>

Or in the case of string keys, where the key follows the rules for identifiers, you can use this shortcut:

<code>print ( foods.fish )  --&gt; 10</code>

<hr/>

Tables are anonymous, they don't have to be stored in any variable, or one table might be stored (by reference) in many variables. For example:

<code>print ( { a = 42 } )  --&gt; table: 01D75990</code>

That table existed even though it was not assigned to a variable.

<code>x = { a = 42 }
y = x</code>

In this example both x and y refer to the <i>same</i> table. The assignment did not make a copy of the table, it made a copy of the reference to the table.

<hr/>

Table constructors in the general form provide the key in brackets:

<code>foods = {
   ["fish"]  = 10,
   ["chips"] = 11,
   ["cake"]  = 12
   }
</code>

This is equivalent to the earlier example.

For other data types you <i>must</i> use brackets for the key, eg.

<code>squares = {
   [2] = 4,
   [3] = 9,
   [4] = 16,
   }
</code>

Both the keys and values can be any type except <b>nil</b>, so a table can contain nested tables, or boolean values, for example.

Lua can also automatically assign keys starting at one, like this:

<code>words = {
  "every",    -- assigned key 1
  "good",     -- assigned key 2
  "boy",      -- assigned key 3
  "deserves", -- assigned key 4
  "fruit",    -- assigned key 5
   }
</code>

Elements in tables are separated by a comma or semicolon. It is acceptable to have a trailing comma or semicolon, to assist in machine-generated tables.

Note that there is a difference between the key "10" (a string) and the key 10 (a number).

By convention, in Lua tables start with one (not zero as in C). The Lua libraries are designed around this convention. You can "manually" put an element at position 0 if you need to:

<code>t = {
   [0] = "zero",
   [1] = "one",
   [2] = "two,
   }
</code>

<hr/>

You can add elements to a table at any time, eg.

<code>words [6] = "bread"  -- add (or replace) the key/value pair</code>

You can remove elements by assigning <b>nil</b> as their value, eg.

<code>words [2] = nil  -- delete entry for key 2</code>

You can also use <b>table.insert</b> to add numerically keyed items to a table. This will shuffle existing keys upwards to make room if required.

Likewise, you can use <b>table.remove</b> to remove numerically keyed items from a table. This will shuffle existing keys downwards where required.

<hr/>

You do not specifically delete tables. Once there are no references to the table the garbage-collector will delete it. One way of encouraging that to happen is to assign <b>nil</b> to any variables which refer to the table:

<code>words = nil  -- finished with table</code>

<hr/>

You can see if a table is empty or not by using the <b>next</b> function:

<code>print (next (words))  --&gt; prints nil if table is empty</code>


name: utils.utf8convert
prototype: s = utils.utf8convert (str)
summary: Encodes a string into a UTF-8 string
doc_name: lua_utils
description:
This encodes a string which is assumed to be non-UTF-8 into a UTF-8 string. 

The function returns a string which is the appropriate UTF-8 encoded string. 
eg.

<code>
print (utils.tohex (utils.utf8convert (string.char (255))))  --&gt; C3BF
</code>

This is intended to allow strings in an ANSI code page to be converted into UTF-8. For example, "Ãˆ" (0xC8) would be converted into 0xC3 0x88.


name: utils.glyph_available
prototype: n = utils.glyph_available (font, glyph)
summary: Returns the glyph index of a glyph (character) in a font
doc_name: lua_utils
description:
This lets you test if a particular glyph can be rendered in the specified font. This lets a script writer see if a suitable Unicode font has been installed when using UTF-8 mode.

For example:

<code>
print (utils.glyph_available ("Arial Unicode MS", 0x2710) )  --&gt; 4439
</code>

Zero will be returned if the glyph is not in the font. Nil will be returned if the gdi32 DLL cannot be loaded or if the function GetGlyphIndicesW is not available from Windows.

The number 31 might be returned which probably indicates that the glyph is not in that font.

Other numbers (other than nil, 0 or 31) would indicate that the glyph is available. The exact number represents the "glyph index" in the font table.

Note that it appears that even if 0 is returned that character might be rendered anyway because Windows uses a "fallback" font if a character is not available in the main font. However whether or not this works seems to depend on what main font is selected (for example, if it is a Unicode font or not).

The intention of this function is to let script (plugin) writers warn users if they are planning to use certain glyphs (for example, mapping symbols) which are not in the currently-selected font.


name: utils.colourcube
prototype: utils.colourcube (which)
summary: Changes the colour cube used by 256-colour ANSI codes
doc_name: lua_utils
description:
There are (at least) two colour cubes which can be used to generate the 216 colours used by 256-colour ANSI. (6 * 6 * 6 = 216). The other colours are fixed: 16 "standard ANSI" colours plus 24 gray-scale ones.

This function lets you choose between the Xterm cube (the default) which favours brighter colours (the gap between colours is: 95 / 40 / 40 / 40) and the Netscape cube which has even colours, with a consistent gap of 51 / 51 / 51 / 51 / 51.

utils.colourcube (1)  -- Use the Xterm cube

utils.colourcube (2)  -- Use the Netscape cube


name: utils.menufontsize
prototype: oldSize = utils.menufontsize (newSize)
summary: Alters the size of the font used in menus
doc_name: lua_utils
description:
For the benefit of players with large monitors, you can set the font size for MUSHclient menus, for example:

<code>
  oldSize = utils.menufontsize (15)
</code>

The font size must be in the range 5 to 30 (points). Other sizes will be ignored. 

In any event, the function returns what the font size was previously. Note that this will probably affect <b>all</b> applications, not just MUSHclient. 

You may want to remember the old font size, and restore the menu font size when MUSHclient loses the focus. On my system, the "normal" size was 11 points.


