Difference between revisions of "Area 51"

From Mudlet
Jump to navigation Jump to search
(Updated documentation for db methods)
Line 19: Line 19:
 
=Database Functions=
 
=Database Functions=
 
:A collection of functions for helping deal with the database.
 
:A collection of functions for helping deal with the database.
 
==db:_sql_convert==
 
;<nowiki>db:_sql_convert(value)</nowiki>
 
:Converts a data value in Lua to its SQL equivalent; notably it will also escape single-quotes to prevent inadvertent SQL injection. In addition, it will convert Lua tables with a _timestamp key to the appropriate time (possibly CURRENT_TIMESTAMP) and Lua tables with a _isNull key to the NULL SQL keyword.
 
  
 
==db:create==
 
==db:create==

Revision as of 12:06, 8 May 2022

This page is for the development of documentation for Lua API functions that are currently being worked on. Ideally the entries here can be created in the same format as will be eventually used in Lua Functions and its sub-sites.

Please use the Area_51/Template to add new entries in the sections below.

Links to other functions or parts in other sections (i.e. the main Wiki area) need to include the section details before the '#' character in the link identifier on the left side of the '|' divider between the identifier and the display text. e.g.

[[Manual:Mapper_Functions#getCustomLines|getCustomLines()]]

rather than:

[[#getCustomLines|getCustomLines()]]

which would refer to a link within the current (in this case Area 51) section. Note that this ought to be removed once the article is moved to the main wiki area!

The following headings reflect those present in the main Wiki area of the Lua API functions. It is suggested that new entries are added so as to maintain a sorted alphabetical order under the appropriate heading.


Basic Essential Functions

These functions are generic functions used in normal scripting. These deal with mainly everyday things, like sending stuff and echoing to the screen.

Database Functions

A collection of functions for helping deal with the database.

db:create

db:create(database name, schema table, force)
Creates and/or modifies an existing database. This function is safe to define at a top-level of a Mudlet script: in fact it is recommended you run this function at a top-level without any kind of guards. If the named database does not exist it will create it. If the database does exist then it will add any columns or indexes which didn’t exist before to that database. If the database already has all the specified columns and indexes, it will do nothing. If an existing column with at least one non-NULL value is missing from the new schema, it will raise an error by default; the user may force the dropping of the column by setting the force argument to true.
The database will be called Database_<sanitized database name>.db and will be stored in the Mudlet configuration directory within your profile folder, which you can find with getMudletHomeDir().
Database tables are called sheets consistently throughout this documentation, to avoid confusion with Lua tables.
The schema table must be a Lua table array containing table dictionaries that define the structure and layout of each sheet
Example
local mydb = db:create("combat_log",
  {
    kills = {
              name = "",
              area = "",
              killed = db:Timestamp("CURRENT_TIMESTAMP"),
              _index = { {"name", "area"} }
            },
    enemies = {
                name = "",
                city = "",
                reason = "",
                enemied = db:Timestamp("CURRENT_TIMESTAMP"),
                _index = { "city" },
                _unique = { "name" },
                _violations = "IGNORE"
               }
  })
The above will create a database with two sheets; the first is kills and is used to track every successful kill, with both where and when the kill happened. It has one index, a compound index tracking the combination of name and area. The second sheet has two indexes, but one is unique: it isn’t possible to add two items to the enemies sheet with the same name.
For sheets with unique indexes, you may specify a _violations key to indicate how the db layer handle cases where the data is duplicate (unique index is violated). The options you may use are:
  • FAIL - the default. A hard error is thrown, cancelling the script.
  • IGNORE - The command that would add a record that violates uniqueness just fails silently.
  • REPLACE - The old record which matched the unique index is dropped, and the new one is added to replace it.
Returns a reference of an already existing database. This instance can be used to get references to the sheets (and from there, fields) that are defined within the database. You use these references to construct queries.
If a database has a sheet named enemies, you can obtain a reference to that sheet by simply doing:
local mydb = db:get_database("my database")
local enemies_ref = mydb.enemieslocal
local name_ref = mydb.enemies.name

Note Note: db:create() supports adding new columns and indexes to existing databases, but this functionality was broken in Mudlet 2.1 due to the underlying Lua SQL binding used being out of date. When you want to add a new column, you have several options:

  • if you are just testing and getting setup, close Mudlet, and delete the Database_<sanitized database name>.db file in your Mudlet folder.
  • if you've already gotten a script and have a fair bit of data with it, or users are already using your script and telling them to delete files on an upgrade is unreasonable, you can use direct SQL to add in a new column. WARNING, this is an expert option, and requires knowledge of SQL to accomplish. You must backup your database file before you start coding this in.
  -- at first, update your db:create schema to have the new field.
  -- then, we'll tell the database to create it if it doesn't exist

  -- fetch the data we've got in our sample database
  local test = db:fetch(ndb.db.people)
  -- this requires at least one entry in the database to work
  if next(test) then
    local _,someperson = next(test)
    
    -- in this example, we want to add an order key. If there is no key, means it doesn't exist yet, so it should be added.
    if someperson.order == nil then
      -- do not do the things you see here elsewhere else. This is a big hack/workaround.
      local conn = db.__conn.namedb
      -- order should be a text field, so note that we specify it's type with TEXT and the default value at the end with ""
      local sql_add = [[ALTER TABLE people ADD COLUMN "order" TEXT NULL DEFAULT ""]]
      conn:execute(sql_add)
      conn:commit()
    end

    -- here is an another example, in one where we need to add a field that is a number
    if someperson.dragon == nil then
      local conn = db.__conn.namedb
      -- observe that we use the REAL type by default instead and a default of 0
      local sql_add = [[ALTER TABLE people ADD COLUMN "dragon" REAL NULL DEFAULT 0]]
      conn:execute(sql_add)
      conn:commit()
    end
  end

db:Null

db:Null()
Returns a table that will be interpreted as the NULL SQL keyword.

db:Timestamp

db:Timestamp(time)
Returns a table that will be converted to an appropriate time. If the time argument is a table, it will be converted to the current OS time; if it is a number, it will be intrepreted as a Unix epoch time; if it is nil, it will be converted to a SQL NULL; it can also have the value of "CURRENT_TIMESTAMP", which will be converted to the corresponding SQL keyword.

Date/Time Functions

A collection of functions for handling date & time.

File System Functions

A collection of functions for interacting with the file system.

Mapper Functions

A collection of functions that manipulate the mapper and its related features.

getCustomLines1, PR #6009 open

lineTable = getCustomLines1(roomID)

This is a replacement for getCustomLines(...) that outputs the tables for the coordinates for the points on the custom line in an order and format that can be fed straight back into an addCustomLine(...) call; similarly the color parameters are also reported in the correct format to also be reused in the same manner. This function is intended to make it simpler for scripts to manipulate such lines.

See also: addCustomLine(), removeCustomLine(), getCustomLines()
Mudlet VersionAvailable in Mudlet ?.??+

Note Note: pending, not yet available. See https://github.com/Mudlet/Mudlet/pull/6009

Parameters
  • roomID:
Room ID to return the custom line details of.
Returns
a table including all the details of the custom exit lines, if any, for the room with the id given.
Example
display getCustomLines1(1)
{
  ["climb Rope"] = {
    attributes = {
      color = { 128, 128, 0 },
      style = "dash dot dot line",
      arrow = false
    },
    points = { { 4.5, 5.5, 3 }, { 4.5, 9.5, 3 }, { 6, 9.5, 3 } } 
  },
  N = {
    attributes = {
      color = { 0, 255, 255 },
      style = "dot line",
      arrow = true
    },
    points = { { -3, 27, 3 } }
  }
}

Note Note: Compare the above example with the corresponding one in getCustomLines(...) and observe that the entry that had the key of 0 in the other function is now, correctly, reported first. The other function was incorrectly coded so as to start the indexing of the points at the value of 0 rather than the normal Lua value of 1, this broke the internal "rules" for Lua so it treated the points as an associative-array type of table with keys of the form 0, 1, ... n-1 rather than the 1, 2, ... n that a list type table requires. Furthermore, it returns a (constant) z-coordinate which is, in fact that of the room that it is from; this is to meet the current requirements for all three coordinates to be provided to addCustomLine(...) though Mudlet currently only offers custom lines on the 2D mapper and they must be entirely on the same level as the starting room (this is a reservation for a potential future extension into the third dimension.)

Additionally the color component details reported in this function are returned as a Lua list (in the order of red, green and blue) which is the format that addCustomLine(...) requires compared to the associative array with keys of "r", "g" and "b" that getCustomLine(...) reports.

mapSymbolFontInfo, PR #4038 closed

mapSymbolFontInfo()
See also: setupMapSymbolFont()

Note Note: pending, not yet available. See https://github.com/Mudlet/Mudlet/pull/4038

returns
  • either a table of information about the configuration of the font used for symbols in the (2D) map, the elements are:
  • fontName - a string of the family name of the font specified
  • onlyUseThisFont - a boolean indicating whether glyphs from just the fontName font are to be used or if there is not a glyph for the required grapheme (character) then a glyph from the most suitable different font will be substituted instead. Should this be true and the specified font does not have the required glyph then the replacement character (typically something like ) could be used instead. Note that this may not affect the use of Color Emoji glyphs that are automatically used in some OSes but that behavior does vary across the range of operating systems that Mudlet can be run on.
  • scalingFactor - a floating point number between 0.50 and 2.00 which modifies the size of the symbols somewhat though the extremes are likely to be unsatisfactory because some of the particular symbols may be too small (and be less visible at smaller zoom levels) or too large (and be clipped by the edges of the room rectangle or circle).
  • or nil and an error message on failure.
As the symbol font details are stored in the (binary) map file rather than the profile then this function will not work until a map is loaded (or initialized, by activating a map window).

moveMapLabel, PR #6014 open

moveMapLabel(areaID/Name, labeID/Text, coordX/deltaX, coordY/deltaY[, coordZ/deltaZ][, absoluteNotRelativeMove])

Re-positions a map label within an area in the 2D mapper, in a similar manner as the moveRoom() function does for rooms and their custom exit lines. When moving a label to given coordinates this is the position that the top-left corner of the label will be positioned at; since the space allocated to a particular room on the map is ± 0.5 around the integer value of its x and y coordinates this means for a label which has a size of 1.0 x 1,0 (w x h) to position it centrally in the space for a single room at the coordinates (x, y, z) it should be positioned at (x - 0.5, y + 0.5, z).

See also: getMapLabels(), getMapLabel().
Mudlet VersionAvailable in Mudlet ?.??+

Note Note: pending, not yet available. See https://github.com/Mudlet/Mudlet/pull/6014

Parameters
  • areaID/Name:
Area ID as number or AreaName as string containing the map label.
  • labelID/Text:
Label ID as number (which will be 0 or greater) or the LabelText on a text label. All labels will have a unique ID number but there may be more than one text labels with a non-empty text string; only the first matching one will be moved by this function and image labels also have no text and will match the empty string. with mo or AreaName as string containing the map label.
  • coordX/deltaX:
A floating point number for the absolute coordinate to use or the relative amount to move the label in "room coordinates" along the X-axis.
  • coordY/deltaY:
A floating point number for the absolute coordinate to use or the relative amount to move the label in "room coordinates" along the Y-axis.
  • coordZ/deltaZ:
(Optional) A floating point number for the absolute coordinate to use or the relative amount to move the label in "room coordinates" along the Z-axis, if omitted the label is not moved in the z-axis at all.
  • absoluteNotRelativeMove:
(Optional) a boolean value (defaults to false if omitted) as to whether to move the label to the absolute coordinates (true) or to move it the relative amount from its current location (false).
Returns
true on success or nil and an error message on failure, if successful it will also refresh the map display to show the result.
Example
-- move the first label in the area with the ID number of 2, three spaces to the east and four spaces to the north
moveMapLabel(0, 2, 3.0, 4.0)

-- move the first label in the area with the ID number of 2, one space to the west, note the final boolean argument is unneeded
moveMapLabel(0, 2, -1.0, 0.0, false)

-- move the second label in the area with the ID number of 2, three and a half spaces to the west, and two south **of the center of the current level it is on in the map**:
moveRoom(1, 2, -3.5, -2.0, true)

-- move the second label in the area with the ID number of 2, up three levels
moveRoom(1, 2, 0.0, 0.0, 3.0)

-- move the second label in the "Test 1" area one space to the west, note the last two arguments are unneeded
moveRoom("Test 1", 1, -1.0, 0.0, 0.0, false)

-- move the (top-left corner of the first) label with the text "Home" in the area with ID number 5 to the **center of the whole map**, note the last two arguments are required in this case:
moveRoom(5, "Home", 0.0, 0.0, 0.0, true)

-- all of the above will return the 'true'  boolean value assuming there are the indicated labels and areas

moveRoom, PR #6010 open

moveRoom(roomID, coordX/deltaX, coordY/deltaY[, coordZ/deltaZ][, absoluteNotRelativeMove])

Re-positions a room within an area, in the same manner as the "move to" context menu item for one or more rooms in the 2D mapper. Like that method this will also shift the entirety of any custom exit lines defined for the room concerned. This contrasts with the behavior of the setRoomCoordinates() which only moves the starting point of such custom exit lines so that they still emerge from the room to which they belong but otherwise remain pointing to the original place.

See also: setRoomCoordinates()
Mudlet VersionAvailable in Mudlet ?.??+

Note Note: pending, not yet available. See https://github.com/Mudlet/Mudlet/pull/6010

Parameters
  • roomID:
Room ID number to move.
  • coordX/deltaX:
The absolute coordinate or the relative amount as a number to move the room in "room coordinates" along the X-axis.
  • coordY/deltaY:
The absolute coordinate or the relative amount as a number to move the room in "room coordinates" along the Y-axis.
  • coordZ/deltaZ:
(Optional) the absolute coordinate or the relative amount as a number to move the room in "room coordinates" along the Z-axis, if omitted the room is not moved in the z-axis at all.
  • absoluteNotRelativeMove:
(Optional) a boolean value (defaults to false if omitted) as to whether to move the room to the absolute coordinates (true) or the relative amount from its current location (false).
Returns
true on success or nil and an error message on failure, if successful it will also refresh the map display to show the result.
Example
-- move the first room one space to the east and two spaces to the north
moveRoom(1, 1, 2)

-- move the first room one space to the west, note the final boolean argument is unneeded
moveRoom(1, -1, 0, false)

-- move the first room three spaces to the west, and two south **of the center of the current level it is on in the map**:
moveRoom(1, -3, -2, true)

-- move the second room up three levels
moveRoom(2, 0, 0, 3)

-- move the second room one space to the west, note the last two arguments are unneeded
moveRoom(2, -1, 0, 0, false)

-- move the second room to the **center of the whole map**, note the last two arguments are required in this case:
moveRoom(2, 0, 0, 0, true)

-- all of the above will return the 'true'  boolean value assuming there are rooms with 1 and 2 as ID numbers

setupMapSymbolFont, PR #4038 closed

setupMapSymbolFont(fontName[, onlyUseThisFont[, scalingFactor]])
configures the font used for symbols in the (2D) map.
See also: mapSymbolFontInfo()

Note Note: pending, not yet available. See https://github.com/Mudlet/Mudlet/pull/4038

Parameters
  • fontName one of:
  • - a string that is the family name of the font to use;
  • - the empty string "" to reset to the default {which is "Bitstream Vera Sans Mono"};
  • - a Lua nil as a placeholder to not change this parameter but still allow a following one to be modified.
  • onlyUseThisFont (optional) one of:
  • - a Lua boolean true to require Mudlet to use graphemes (character) only from the selected font. Should a requested grapheme not be included in the selected font then the font replacement character (�) might be used instead; note that under some circumstances it is possible that the OS (or Mudlet) provided color Emoji Font may still be used but that cannot be guaranteed across all OS platforms that Mudlet might be run on;
  • - a Lua boolean false to allow Mudlet to get a different glyph for a particular grapheme from the most suitable other font found in the system should there not be a glyph for it in the requested font. This is the default unless previously changed by this function or by the corresponding checkbox in the Profile Preferences dialogue for the profile concerned;
  • - a Lua nil as a placeholder to not change this parameter but still allow the following one to be modified.
  • scalingFactor (optional): a floating point value in the range 0.5 to 2.0 (default 1.0) that can be used to tweak the rectangular space that each different room symbol is scaled to fit inside; this might be useful should the range of characters used to make the room symbols be consistently under- or over-sized.
Returns
  • true on success
  • nil and an error message on failure. As the symbol font details are stored in the (binary) map file rather than the profile then this function will not work until a map is loaded (or initialised, by activating a map window).

Miscellaneous Functions

Miscellaneous functions.

getCharacterName, PR #6023 merged

getCharacterName()
Returns the name entered into the "Character name" field on the Connection Preferences form. Can be used to find out the name that might need to be handled specially in scripts or anything that needs to be personalized to the player. If there is nothing set in that entry will return an empty string.
See also: sendCharacterName(), sendCharacterPassword(), sendCustomLoginText(), getCustomLoginTextId(). (These functions are pending in a separate PR and are not yet available!)

Note Note: Only available in PTBs currently.

Example
lua send("cast 'glamor' " .. getCharacterName())

You get a warm feeling passing from your core to the tips of your hands, feet and other body parts.
A small twittering bird settles on your shoulder and starts to look adoringly at you.
A light brown faun gambles around you and then nuzzles your hand.
A tawny long-haired cat saunters over and start to rub itself against your ankles.
A small twittering bird settles on your shoulder and starts to look adoringly at you.
A light brown faun gambles around you and then nuzzles your hand.
A small twittering bird settles on your shoulder and starts to look adoringly at you.
A mangy dog trots up to you and proceeds to mark the bottom of your leggings.

Development notes: originally proposed alongside four other functions in PR #3952 to enable game server log-in to be scripted with the simultaneous movement of that functionality from the Mudlet application core code to a predefined doLogin() function that may be replaced for more sophisticated requirements - but it was extracted and put through separately in order to help meet a functional requirement that was discussed in Discord IIRC. slysven (talk) 02:47, 3 April 2022 (UTC)

getCustomLoginTextId, PR #3952 open

getCustomLoginTextId()

Returns the Id number of the custom login text setting from the profile's preferences. Returns 0 if the option is disabled or a number greater than that for the item in the table; note it is possible if using an old saved profile in the future that the number might be higher than expected. As a design policy decision it is not permitted for a script to change the setting, this function is intended to allow a script or package to check that the setting is what it expects.

Introduced along with four other functions to enable game server log-in to be scripted with the simultaneous movement of that functionality from the Mudlet application core code to a predefined doLogin() function, a replacement for which is shown below.

See also: getCharacterName(), sendCharacterName(), sendCustomLoginText(), sendPassword().

Note Note: Not available yet. See https://github.com/Mudlet/Mudlet/pull/3952

Only one custom login text has been defined initially:

Predefined custom login texts
Id Custom text Introduced in Mudlet version
1 "connect {character name} {password}" TBD

The addition of further texts would be subject to negotiation with the Mudlet Makers.

Example
-- A replacement for the default function placed into LuaGlobal.lua to reproduce the previous behavior of the Mudlet application:
function doLogin()
  if getCustomLoginTextId() ~= 1 then
    -- We need this particular option but it is not permitted for a script to change the setting, it can only check what it is
    echo("\nUnable to login - please select the 'connect {character name} {password}` custom login option in the profile preferences.\n")
  else
    tempTime(2.0, [[sendCustomLoginText()]], 1)
  end
end

sendCharacterName, PR #3952 open

sendCharacterName()

Sends the name entered into the "Character name" field on the Connection Preferences form directly to the game server. Returns true unless there is nothing set in that entry in which case a nil and an error message will be returned instead.

Introduced along with four other functions to enable game server log-in to be scripted with the simultaneous movement of that functionality from the Mudlet application core code to a predefined doLogin() function that may be replaced for more sophisticated requirements.

See also: getCharacterName(), sendCharacterPassword(), sendCustomLoginText(), getCustomLoginTextId().

Note Note: Not available yet. See https://github.com/Mudlet/Mudlet/pull/3952

sendCharacterPassword, PR #3952 open

sendCharacterPassword()

Sends the password entered into the "Password" field on the Connection Preferences form directly to the game server. Returns true unless there is nothing set in that entry or it is too long after (or before) a connection was successfully made in which case a nil and an error message will be returned instead.

Introduced along with four other functions to enable game server log-in to be scripted with the simultaneous movement of that functionality from the Mudlet application core code to a predefined doLogin() function, reproduced below, that may be replaced for more sophisticated requirements.

See also: getCharacterName(), sendCustomLoginText(), getCustomLoginTextId(), sendCharacterName().

Note Note: Not available yet. See https://github.com/Mudlet/Mudlet/pull/3952

Example
-- The default function placed into LuaGlobal.lua to reproduce the previous behavior of the Mudlet application:
function doLogin()
  if getCharacterName() ~= "" then
    tempTime(2.0, [[sendCharacterName()]], 1)
    tempTime(3.0, [[sendCharacterPassword()]], 1)
  end
end

sendCustomLoginText, PR #3952 open

sendCustomLoginText()

Sends the custom login text (which does NOT depend on the user's choice of GUI language) selected in the preferences for this profile. The {password} (and {character name} if present) fields will be replaced with the values entered into the "Password" and "Character name" fields on the Connection Preferences form and then sent directly to the game server. Returns true unless there is nothing set in either of those entries (though only if required for the character name) or it is too long after (or before) a connection was successfully made or if the custom login feature is disabled, in which case a nil and an error message will be returned instead.

Introduced along with four other functions to enable game server log-in to be scripted with the simultaneous movement of that functionality from the Mudlet application core code to a predefined doLogin() function, a replacement for which is shown below.

See also: getCharacterName(), sendCharacterName(), sendPassword(), getCustomLoginTextId().

Note Note: Not available yet. See https://github.com/Mudlet/Mudlet/pull/3952

Only one custom login text has been defined initially:

Predefined custom login texts
Id Custom text Introduced in Mudlet version
1 "connect {character name} {password}" TBD

The addition of further texts would be subject to negotiation with the Mudlet Makers.

Example
-- A replacement for the default function placed into LuaGlobal.lua to reproduce the previous behavior of the Mudlet application:
function doLogin()
  if getCustomLoginTextId() ~= 1 then
    -- We need this particular option but it is not permitted for a script to change the setting, it can only check what it is
    echo("\nUnable to login - please select the 'connect {character name} {password}` custom login option in the profile preferences.\n")
  else
    tempTime(2.0, [[sendCustomLoginText()]], 1)
  end
end

Mudlet Object Functions

A collection of functions that manipulate Mudlets scripting objects - triggers, aliases, and so forth.

Networking Functions

A collection of functions for managing networking.

String Functions

These functions are used to manipulate strings.

Table Functions

These functions are used to manipulate tables. Through them you can add to tables, remove values, check if a value is present in the table, check the size of a table, and more.

Text to Speech Functions

These functions are used to create sound from written words. Check out our Text-To-Speech Manual for more detail on how this all works together.

UI Functions

These functions are used to construct custom user GUIs. They deal mainly with miniconsole/label/gauge creation and manipulation as well as displaying or formatting information on the screen.

Discord Functions

All functions to customize the information Mudlet displays in Discord's rich presence interface. For an overview on how all of these functions tie in together, see our Discord scripting overview.