Furnarchy 2.2 Scripting API
Built-in Functions Listing

Built-in Functions
Clipboard Functions
string getClipboard( )

Returns the ASCII string currently stored in the clipboard.

getClipboard( string str )

Stores the string str in the clipboard.

Conversion Functions
int base220ToInt( string base220 )

Converts the number encoded as a base-220 string, base220, into an integer.

int base95ToInt( string base95 )

Converts the number encoded as a base-95 string, base95, into an integer.

int furcToInt( string base95 )

This is a synonym for base95ToInt.

string intToBase220( int n, int width )

Encodes the integer n as a base-220 string of width digits.

string intToBase95( int n, int width )

Encodes the integer n as a base-95 string of width digits..

string intToFurc( int n )

This is a synonym for intToBase95.

int stringToUint( string str, [int radix] )

Converts a string-encoded number str in the base specified by radix into an unsigned integer.

radix can be any number in the range [2,36].

If radix is omitted, radix=10 is implied.

string toChar( int x )

Converts the ordinal x to its string-character representation.

FYI: To do the reverse (get the ordinal of a string-character), just use the index operator ([]) on the string.

float toFloat( any x )

Converts x (which may be any type) into a float.

int toInt( any x )

Converts x (which may be any type) into a signed integer.

string toString( any x )

Converts x (which may be any type) into a string.

string toTypename( any x )

Returns the typename of x.

string uintToString( int n, [int radix] )

Encodes n as a string in the base specified by radix.

radix may be any number in the range [2,36].

If radix is omitted, radix=10 is implied.

Database Functions

Every script has access to one DB file where it can write and read information. To read or write to a DB, you must call dbOpen first. When you're done reading or manipulating the DB data, call dbClose to close the DB and commit all changes to disk.

dbClose( )

Closes the DB file, comitting any changes to disk.

int dbCount( [string section] )

Counts the number of fields inside a DB section named section.

If section is omitted, the global section ("") is used.

This operation is only valid after a call to dbOpen.

int dbCountSections( )

Counts the number of sections inside the database.

Does not include the global section.

This operation is only valid after a call to dbOpen.

dbErase( string field, [string section] )

Erases a field named field in section section.

If section is omitted, the global section ("") is used.

This operation is only valid after a call to dbOpen.

dbEraseSection( [string section] )

Erases the section named section and all fields contained.

If section is omitted, the global section ("") is used.

This operation is only valid after a call to dbOpen.

dbOpen( )

Opens the DB file for reading/writing.

dbPurge( )

Clears all fields and sections in the DB.

This operation is only valid after a call to dbOpen.

string dbRead( string field, [string section] )

Reads the string contained in field in section section.

If the field doesn't exist, the returned string will be 0-length.

If section is omitted, the global section ("") is used.

This operation is only valid after a call to dbOpen.

table dbReadAt( int field_index, [string section] )

Retrieves a field by its index specified by field_index inside section section.

Note that DB fields are stored in reverse order, so if field_index is 0, dbReadAt will return the last field in section section.

The return value is an associative table with the following keys.
KeyTypeDescription
keystringThe name of the field.
valuestringThe value of the field.

If the field doesn't exist, dbReadAt will return a null.

If section is omitted, the global section ("") is used.

This operation is only valid after a call to dbOpen.

string dbReadSectionName( int section )

Reads the name of the section specified by section.

If the section doesn't exist, the returned string will be 0-length.

Note that DB sections are stored in reverse order, so if section is 0, dbReadSectionName will return the last section.

This operation is only valid after a call to dbOpen.

dbWrite( string field, string value, [string section] )

Writes the string value to the field named field in the section .

If section is omitted, the global section ("") is used.

This operation is only valid after a call to dbOpen.

Math Functions
int abs( int number )

Returns the absolute of number.

float acos( int number )

Returns the arccosine of number.

float asin( int number )

Returns the arcsine of number.

float atan( int number )

Returns the arctangent of number.

float cos( int number )

Returns the cosine of number.

float sqrt( int number )

Returns the square root of number.

int rand( [int range] )

Returns a pseudorandom integer in the unsigned range [0,range).

If range is omitted, the range will be (0,0x7FFFFFFF].

randSeed( int seed )

Seeds the random number generator.

The random number generator is automatically seeded with the system time (in milliseconds) before a script begins.

float sin( int number )

Returns the sine of number.

float tan( int number )

Returns the tangent of number.

Miscellaneous Functions
bool altState( )

Returns true if the ALT key is down, false otherwise.

collectGarbage( [bool force] )

Frees any unreferenced objects used by the script.

If force is false, resources are only freed if the memory usage exceeds an internal limit.

If force is omitted, force=false is implied.

Note that furnarchy periodically collects garbage on its own. Only the most resource intensive scripts should ever need to use this function.

command( string cmd, [bool noecho] )

Sends a '@'-style command through Furnarchy. The '@' prefix is implied.

If noecho is true, Furnarchy won't echo the command in the chat buffer, like it normally would if a user typed it his or herself.

If noecho is omitted, noecho=false is implied.

bool ctrlState( )

Returns true if the CONTROL key is down, false otherwise.

errSpeak( ... )

Converts and combines all parameters passed into a string, prints it to the console, then logs it in the error log.

exit( [int exit_code] )

Terminates the script with exit code exit_code.

exit_code should be non-zero to indicate a failure.

If exit_code is omitted, 0 will be used.

If an onKill event-handler has been defined, execution will jump there before the script terminates.

table getArgs( )

Retrieves the command line arguments used to launch the script.

The command line arguments are returned as an indexed table, with the first (0) index being the script's name, and the following indices being passed arguments.

int getScriptID( )

Retrieves the internal script ID.

ignore( string s )

Ignores s. If s begins with a '@', it indicates a channel name, rather than a player name.

This function depends on memlocs, so it will only work with the most recently supported client build.

unignore( string s )

Unignores s. If s begins with a '@', it indicates a channel name, rather than a player name.

This function depends on memlocs, so it will only work with the most recently supported client build.

import( string script )

Executes another script within this script, inheriting all global variables the script declares.

script must be the name of a script in the "scripts/imports" folder, without the ".gm" extension.

int length( any x )

Returns the length of variable x.

If x is a string, the return value is the length of the string.

If x is a table, the return value is the number of elements in the table.

If x is anything else, the return value is 0.

log( ... )

Converts and combines all parameters into a string and writes them to the script's personal log file, stored in the "scripts\logs" folder.

print( ... )

Converts and combines all parameters into a string and writes them to the stdout console.

int rgb( int red, int green, int blue )

Create an RGB color value.

table rgbUnpack( int color )

Splits up a color value into its red, green and blue components.

The returned table has 3 keys, "r", "g", and "b", which hold the red, green, and blue values, respectively.

bool shiftState( )

Returns true if the SHIFT key is down, false otherwise.

speak( ... )

Converts and combines all parameters into a string and prints them to the chat buffer.

Module Functions

Module functions allow communication with modules that support it.

int modFind( string uuid )

Looks for a module with a matching UUID string specified by uuid.

The UUID of a module can be found in its "module.ini" file (if it has one).

Returns the index of the module, or -1 if the module wasn't found.

int modMsg( int mod, string msg )

Sends a string module message to the module identified by index mod.

Returns the result of the message as an integer.

Warning!
This only works with modules that accept messages as strings. Trying to send a message to a module that expects something else could result in a crash.

int modMsgSz( int mod, string msg )

Sends a string module message to the module identified by index mod.

Returns the result of the message as a string.

Warning!
This only works with modules that accept messages as strings and return a C-string as a result. Trying to send a message to a module that expects something else could result in a crash.

Network Functions
int countInbound( )

Counts how many inbound network lines have been processed.

int countOutbound( )

Counts how many outbound network lines have been processed.

netIn( ... )

Combines strings and injects them as inbound data.

Each parameter must be a string.

int netInLine( ... )

Combines strings and injects them as inbound data.

The combined string is automatically terminated with a linefeed, and counts as a single command. The return value is a number that uniquely identifies this line in the inbound queue.

Each parameter must be a string.

netOut( ... )

Combines strings and sends them as outbound data.

Each parameter must be a string.

int netOutLine( ... )

Combines strings and sends them them as outbound data.

The combined string is automatically terminated with a linefeed, and counts as a single command. The return value is a number that uniquely identifies this line in the outbound queue.

Each parameter must be a string.

table netScan( string pattern, string subject )

Matches and extracts common formatted data from simple network lines.

This is similar to scanf or sscanf in C, where pattern defines the format of the subject string as a combination of literal characters and format specifiers (see below). The result is an indexed table containing each scanned element in order from left-to-right. Depending on the format specifier, each respective table element returned may either be an integer or a string. If the pattern string does not match the subject string, null is returned.

Example (Extracting name and color data from a portrait string)
global onInbound = function( line )
{
 // Match the characters "]f", then capture a color-code string,
 // 3 more characters (the gender, species and digo bytes),
 // and all remaining characters (the name).
 s = netScan( "]f%K%3c%*c", line );
 if (s)
 {
    speak( s[ 2 ], "'s color-code is ", s[ 0 ], s[ 1 ] );
 }
};

Format specifiers generally have the form %[length]type. The applicability or legality of the length field depends on the type.

netScan Format Specifiers
SpecifierDescription
%c Any one Character. May be augmented with a length such as %3c to read in 3 any characters or %*c to read in all characters that follow. Returns as a string.
%s A furcadia byte-string (A base-220 digit followed by a string). Returns as a string.
%k An old-style furcadia color-code (10-characters long, not including the 3 trailing GSD bytes). Returns as a string.
%K A new-style furcadia color-code (variable-length, not including the 3 trailing GSD bytes). Returns as a string.
%n A single-digit base-95 number. May be augmented with a length such as %2n to read in a 2-digit base-95 number. Returns as an integer.
%N A single-digit base-220 number. May be augmented with a length such as %2N to read in a 2-digit base-220 number. Returns as an integer.
%% A literal % character. Isn't captured so it doesn't count towards the overall length of the returned table.

table parseChat( string line )

Parses common chat text.

After successfully parsing line, an associative table is returned with various fields defined according to the text's determined type, which can be gleamed from the table's type field. Refer to the table below for which fields are defined for which types.

The various constant values the type field can be set to are defined in the "parsechat" import script.

If the line cannot be parsed, or is not a chat line, null is returned.

Example (Catching other people's speech.)
// This import is required for the parseChat() function.
import( "parsechat" );

global onInbound = function( line )
{
 // Only bother with chat lines.
 if (line[ 0 ] == '(')
 {
     chat = parseChat( line );
     if (chat && chat.type == CHAT_SPEECH)
     {
        speak( chat.from, " just said: ", chat.message );
     }
 }
};

parseChat Returned Table Fields
type valueDescriptionOther fields
CHAT_WHISPERA whisper.
  • from - Sender's name.
  • from_short - Sender's short-name.
  • message - Message.

CHAT_SHOUTA shout.
  • from - Sender's name.
  • from_short - Sender's short-name.
  • message - Message.

CHAT_SPEECHRegular player speech.
  • from - Sender's name.
  • from_short - Sender's short-name.
  • message - Message.

CHAT_EMOTEAn emote.
  • from - Sender's name.
  • from_short - Sender's short-name.
  • message - Action.

CHAT_DESCHEADThe "You see..." part of a description.
  • player - Player's name.
  • player_short - Player's short-name.

CHAT_DESCBODYThe body of a description.
  • player_short - Player's short-name.
  • body - Description body.

CHAT_EMITAn emit.
  • message - Message.

CHAT_COOKIEYou received a cookie.
  • from - Sender's name.
  • note - Note (may be empty).

CHAT_SUMMONA summon request.
  • from - Sender's name.
  • from_short - Sender's short-name.

CHAT_JOINA join request.
  • from - Sender's name.
  • from_short - Sender's short-name.

CHAT_SUMMONEDYou've been summoned.
  • from - Summoner's name.
  • from_short - Summoner's short-name.

CHAT_JOINEDYou've been joined.
  • from - Joiner's name.
  • from_short - Joiner's short-name.

CHAT_DECLINEDYour summon/join request has been declined.
  • from - Decliner's name.
  • from_short - Decliner's short-name.

Regular Expression Functions

Regex functions provide basic matching and substitution operations used in other languages. The flavor of regular expressions used are PCRE, which support perl constructs, plus some.

string reCap( int index )

Retrieves a backreferenced (captured) substring from the last match or substitute operation.

index values 1-9 are the first through ninth capture blocks.

index value 0 is a copy of the entire matched subject string.

If the last match or substitute operation failed, reCap will return a 0-length string.

bool reMatch( string subject, string op )

Deprecated. Don't use it if you know what's good for you.

bool reMatch2( string subject, string regex, [string flags] )

Matches the Perl-compatible regular expression specified by regex to the subject string subject.

Any combination of the following letters may be specified in flags to change the behavior of the match:
  • "i" - case insensitive
  • "g" - global (find all matches)
  • "u" - ungreedy (shortest match)
  • "v" - invert (succeed if no match)

string reSubst( string subject, string op )

Deprecated. Don't use it if you know what's good for you.

string reSubst2( string subject, string regex, string replace, [string flags] )

Matches the Perl-compatible regular expression specified by regex to the subject string subject and replaces the matching substring with replace.

The replacement string replace may use "backreferences" to refer to captured substrings in regex. Backreferences are similar to those in sed, where "\1" is a backreference to the first captured substring, and so on.

The return value is the subject string after all substitutions have been made.

Any combination of the following letters may be specified in flags to change the behavior of the match:
  • "i" - case insensitive
  • "g" - global (find all matches)
  • "u" - ungreedy (shortest match)
  • "v" - invert (succeed if no match)

String Functions
string asciiToLatin( string s )

Converts XML entity references in the string s to Latin-1 characters, where possible.

int strCaseCmp( string a, string b )

Performs a case-insensitive comparison of a and b.

If a is "less" than b, the return value will be < 0.

If b is "less" than a, the return value will be > 0.

If a is identical to b, the return value will be 0.

string strCat( ... )

Converts and combines all parameters into a single string.

int strCmp( string a, string b )

Performs a case-sensitive comparison of a and b.

If a is "less" than b, the return value will be < 0.

If b is "less" than a, the return value will be > 0.

If a is identical to b, the return value will be 0.

string strEsc( string subject, [int ch] )

Escapes all instances of the character ch in subject.

Escaping is done by inserting a '\' character before all un-escaped instances of ch.

int strFirst( string subject, string delims )

Searches for the first index of any character in delims in subject.

Returns null if not found.

int strLast( string subject, string delims )

Searches for the last index of any character in delims in subject.

Returns null if not found.

string strLwr( string subject )

Returns a lowercase version of subject.

string strRev( string subject )

Returns a reversed version of subject.

int strStr( string subject, string substr )

Searches for the first index of the substring substr in subject.

If not found, the return value is null.

string strSub( string str, int off, [int len] )

Extracts a substring from str len characters long, starting from index off.

If len is omitted, the substring extends to the end of the str.

table strTok( string subject, string delims )

Splits subject into an indexed table of strings delimited by any characters found in delims.

table strTokArgs( string subject )

Splits subject into and indexed table of strings delimited by whitespace, unless escaped or within quotes, double-quotes, or backticks.

string strUpr( string subject )

Returns an uppercase version of subject.

string toShortname( string name )

Returns the shortname version of a string.

Table Functions
string join( table t, string separator )

Flattens table t to a string, with separator between each element.

table map( table t, function fn )

Calls function for each item in table t, storing the return values in a new table.

fn should have the signature function( x ) and may be an anonymous or existing function.

Example
t = map( { 1, 2, 3 }, function( x ) { return x + 1; } );
// this will print "{ 2, 3, 4 }" into the chat buffer.
speak( t );

table slice( table t, {table range, ...} )

Creates a table whose contents are ranges of elements in table t specified by one or more slice ranges.

Each range is a two-element indexed table--the offset and the length, in that order. The length of the range may be omitted, or a negative number used, to indicate a range extending to the end of the table.

If no slice ranges are passed, the returned table will be a copy of t. This can be a simple way of creating copies of tables.

When slicing, t should only contain indexed elements (i.e., be a pure array without associative elements), otherwise you may get some strange results.

Example
t = slice( { "a", "b", "c", "d" }, { 0, 2 }, { 3, 1 } );
// t now contains { "a", "b", "d" }.

table split( string str, string separator )

Splits up the string s into a table of its substrings. The substrings within s are separated by the string separator.

This is similar to the strTok function, but while strTok's substrings are separated by any character in a string of delimeters, split's substrings are separated by an entire string.

Terminal Functions

Terminals provide another way for scripts to interact with the user by giving them their very own, customizable input/output window. Scripts can create and manage as many terminals as they want (within reason).

To fully use terminals, a script must import the import script "term"

int termCreate( [table atts] )

Create a new terminal and return its ID.

The table atts may be passed to initialize the terminal with certain attributes. See termSet for a full list of attributes.

Returns the ID of the terminal. By default, a unique ID is assigned to each terminal when it's created, but this behavior may be overidden by defining the "id" key in the atts table.

termDestroy( int id )

Destroys a terminal by ID specified by id.

If more than one terminal shares the ID, all will be destroyed.

This will trigger the "onDestroy" event-handler specified in a terminal's attributes.

table termGet( int id )

Retrieves all attributes of a terminal specified by id. If more than one terminal shares the ID, only the first's attributes will be returned.

If the terminal doesn't exist, a null will be returned.

termPrint( int id, string line, [int style, [int color]] )

Prints a line of text to the output of a terminal identified by id. Supported XML tags, character entity references, and furcadia smiley codes will be evaluated and applied.

If more than one terminal shares the same ID, line will be printed on all of them.

If either style or color are passed, they will override the style and color of all text in line.

To override color without overriding style, pass a null in place of style.

termSet( int id, table atts )

Sets the attributes of a terminal identified by id to those in the associative table atts.

If more than one terminal shares the ID, all will have their attributes set.

Attributes that may be retrieved or set.
KeyTypeDescription
idintTerminal identifier.
titlestringTerminal window title.
onDestroyfunction Function of signature function( int id ) called when the terminal is being destroyed.
onInputfunction Function of signature function( int id, string input ) called when the player enters something in the input buffer.
fontassociative table An associative table with the keys name and/or height. The name value is the string name of the font and the height value is the integer height of the font.
bgColorsassociative table An associative table with the keys input and/or output. Each should be set to a color value returned by the rgb function, defining their background colors.
typesassociative table

Specifies the style and color of intrinsic text types.

Possible keys are:

  • input
  • output
  • link
  • success
  • warning
  • error
  • channel
  • whisper
  • emote
  • emit
  • myspeech
  • bcast
  • roll
  • shout
  • trade
  • dragonspeak
  • notify
  • query
  • highlight
  • log
  • history
  • furclink
  • cmdlink
  • name
  • f2cmdlink

Each key should have yet another associative table as its value, with keys style and/or color. The style value is a combination of TERMSTYLE_x flags defined in the import script "term", and the color value is a color returned by the rgb function.

An example of setting some terminal attributes.
/* Create the terminal. */
term_id = termCreate( );

/* Set some attributes. */
termSet( term_id, { title="Raw terminal (" + getName( ) + ")",
                   onDestroy=onTermDestroy,
                   onInput=onTermInput,
                   font={ name="Courier New" },
                   types={ input={ color=rgb( 96, 0, 0 ), style=TERMSTYLE_BOLD } }
                 } );

termWrite( int id, string line, [int style, [int color]] )

Writes a line of text to the output of a terminal identified by id.

If more than one terminal shares the same ID, line will be printed on all of them.

If either style or color are passed, they will override the style and color of all text in line.

To override color without overriding style, pass a null in place of style.

Time Functions
int getTime( )

Returns the current UTC time as the number of seconds since January 1, 1970.

int toLocalTime( int utc )

Converts UTC time into the local timezone.

The return value is an associative table with the following keys.
KeyTypeDescription
mon int The current month.
yday int The day of the year.
mday int The day of the month.
sec int The current second.
hour int The current hour. (24hr)
min int The current minute.
wday int The day of the week.
year int The current year.
isdst int Whether we're in DST (Daylight Savings Time) or not.

int uptime( )

Returns how many seconds the client has been running.

Window Functions
flashWindow( )

If the window is not currently the active, foreground window, this causes the window to flash.

string getWindowTitle( )

Retrieves the window's title.

setWindowTitle( string title )

Set the window title.

Be nice and restore it to the old value in your onKill() handler if you change it.

World Functions
badgeCancel( )

Cancels any badges/specitags that will be displayed before the next line of text in the chat buffer.

Call this to prevent a badge showing up after you've cancelled chats/whispers/shouts.

desctag( string tag )

Sets a tag in the player's desc to tag. Pass an empty string to clear it.

Furnarchy will send the updated desc to the server immediately.

Desctags are strings Furnarchy appends to the end of the player's description, but aren't logically considered part of the description. Each script is has a single desctag slot. This function sets this script's desctag slot's value, but doesn't interfere with others.

string getColors( )

Returns the player's complete color code.

string getDesc( )

Returns the player's description.

table getMonsterInfo( int guid ) or table getMonsterInfo( string name )

Retrieve information on an avatar via name or guid.

If successful, an associative table will be returned containing information on the avatar. If the avatar cannot be found, null is returned.

getMonsterInfo Returned Table Fields
NameDescription
guidThe GUID of the monster.
nameThe name of the monster.
posAn associative table with the x and y elements set to the position of the monster.
frameThe avatar frame number.
visibleNon-zero if the avatar is visible by the player.
has_profileNon-zero if the avatar has a profile page.
colorThe color-code string of the avatar.

table getMonsters( )

Retrieves all the monsters that currently exist.

The return value is an indexed table containing the GUIDs of all existing monsters.

string getName( )

Returns the player's name.

table getPos( )

Returns the current camera position.

The camera position is returned as an associative array, with the keys "x" and "y" set to the x and y positions of the camera, respectively.