Manual:Lua Functions

From Mudlet
Jump to navigation Jump to search

Function Categories

Label/Window creation/manipulation Functions: These functions are used to construct custom user GUIs. They deal mainly with miniconsole/label/gauge creation and manipulation.

   createMiniConsole()
   createLabel()
   createGauge()

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.

String Functions

Scripting Object Functions

Mapper Functions

Miscellaneous Functions

Label/Window creation/manipulation Functions

Table Functions

String Functions

string.cut

string.cut(s, maxLen)

Cut string to specified maximum length.

Parameters:

    s:
    maxLen:

Usage:

    Following call will return 'abc'.
    string.cut("abcde", 3)

You can easily pad string to certain length. Example bellow will print 'abcde ' e.g. pad/cut string to 10 characters.

     local s = "abcde"
     s = string.cut(s .. "          ", 10)   -- append 10 spaces
     echo("'" .. s .. "'")

string.enclose

string.enclose(s, maxlevel)

Enclose string by long brackets.

Parameters:

    s:
    maxlevel:

string.ends

string.ends(String, Suffix)

Test if string is ending with specified suffix.

Parameters:

    String:
    Suffix:

See also:

    string.starts()

string.findPattern

string.findPattern(text, pattern) Return first matching substring or nil.

Parameters

   text:
   pattern:

Usage: Following example will print: "I did find: Troll" string.

    local match = string.findPattern("Troll is here!", "Troll")
    if match then
    echo("I did find: " .. match)
    end

This example will find substring regardless of case.

   local match = string.findPattern("Troll is here!", string.genNocasePattern("troll"))
   if match then
   echo("I did find: " .. match)
   end

Return value:

   nil or first matching substring 

See also:

   string.genNocasePattern()

string.genNocasePattern

string.genNocasePattern(s)

Generate case insensitive search pattern from string.

Parameters

   s:

Usage: Following example will generate and print "123[aA][bB][cC]" string.

  echo(string.genNocasePattern("123abc"))

Return value:

  case insensitive pattern string 

string.starts

string.starts(String, Prefix) Test if string is starting with specified prefix. Parameters:

    String:
    Prefix:

See also:

    string.ends()

string.trim

string.trim (s) Trim string (remove all white spaces around string).

Parameters:

    s:

Usage: Example will print 'Troll is here!'.

     local str = string.trim("  Troll is here!  ")
     echo("'" .. str .. "'")

string:split

string:split(delimiter) Splits a string into a table by the given delimiter.

Parameters:

   delimiter:

Usage: Split string by ", " delimiter.

    names = "Alice, Bob, Peter"
    name_table = names:split(", ")
    display(name_table)

Previous code will print out:

   table {
   1: 'Alice'
   2: 'Bob'
   3: 'Peter'
   }

Return value:

   array with split strings

string:title

string:title() Capitalize first character in a string.

Usage: Variable testname is now Anna.

     testname = string.title("anna")

Example will set test to "Bob".

     test = "bob"
     test = string.title(test)

Scripting Object Functions

Mapper Functions

These are functions that are to be used with the Mudlet Mapper. The mapper is designed to be MUD-generic - it only provides the display and pathway calculations, to be used in Lua scripts that are tailored to the MUD you're playing. For a collection of pre-made scripts and general mapper talk, visit the http://forums.mudlet.org/viewforum.php?f=13[mapper section] of the forums.

To register a script as a mapping one with Mudlet (so Mudlet knows the profile has one and won't bother the user when they open the map), please do this in your script:

mudlet = mudlet or {}; mudlet.mapper_script = true


searchRoom

searchRoom (room name)

Searches for rooms that match (by case-insensitive, substring match) the given room name. It returns a key-value table in form of roomid = roomname, like so:

display(searchRoom("master"))

--[[ would result in:
table {
  17463: 'in the branches of the Master Ravenwood'
  3652: 'master bedroom'
  10361: 'Hall of Cultural Masterpieces'
  6324: 'Exhibit of the Techniques of the Master Artisans'
  5340: 'office of the Guildmaster'
  19067: 'the master's gallery'
  21546: 'the Grand Master's Chambers'
  6592: 'hall before the Master Chambers'
  4395: 'customs Office and Harbourmaster's'
  18978: 'the master's salon'
  1622: 'before the office of the harbourmaster'
  18869: 'Master's gallery and reception suite'
  14456: 'north of the Master Gear'
  14624: 'beastmaster's hangout'
  9078: 'chambers of the Master of the Bloodhunt'
  6593: 'Master Quettle's Chambers'
  10210: 'the chambers of Master Blasterson'
  14465: 'south of the Master Gear'
  5341: 'the chamber of the Guildmaster'
  7712: 'central hall in the beastmaster apartments'
  2004: 'office of the guildmaster'
  14457: 'the Master Gear'
  1337: 'before the Master Ravenwood Tree'
}
]]

If no rooms are found, then an empty table is returned.

createMapper

createMapper(x, y, width, height)

Creates a miniconsole window for mapper to render in, the with the given dimensions. You can only create one at a time at the moment.

createMapper(0,0,300,300) -- creates a 300x300 mapper top-right of Mudlet
setBorderLeft(305) -- adds a border so text doesn't underlap the mapper display

centerview

centerview (room number)

Centers the map view onto the given room ID. The map must be open to see this take effect. This function can also be used to see the map of an area if you know the number of a room there and the area and room are mapped.

gotoRoom

gotoRoom (roomID) Speedwalks you to the given room from your current room if it is able and knows the way. You must turn the map on for this to work, else it will return "(mapper): Don't know how to get there from here :(".

getRoomExits

getRoomExits (roomID) Returns the currently known non-special exits for a room in an key-index form: exit = exitroomid, ie:

table {
  'northwest': 80
  'east': 78
}

addRoom

addRoom(roomID)

Creates a new room with the given ID, returns true if the room was successfully created.


lockRoom

lockRoom (roomID, lock = true/false)

Locks a given room id from future speed walks (-> never enter that room).

lockRoom(1, true) -- locks a room if from being walked through when speedwalking.
lockRoom(1, false) -- unlocks the room, adding it back to possible rooms that can be walked through.


setRoomWeight

setRoomWeight(roomID, weight) Sets a weight to the given roomID. By default, all rooms have a weight of 0 - the higher the weight is, the more likely the room is to be avoided for pathfinding. For example, if travelling across water rooms takes more time than land ones - then you'd want to assign a weight to all water rooms, so they'd be avoided if there are possible land pathways.

setRoomWeight(1532, 1) -- avoid using this room if possible, but don't completely ignore it

To completely avoid a room, make use of lockRoom().


getAreaTable

getAreaTable()

Returns a key(area name)-value(area id) table with all known areas and their IDs. There is an area with the name of and an ID of 0 included in it, you should ignore that.

-- example function that returns the area ID for a given area

function findAreaID(areaname)
  local list = getAreaTable()

  -- iterate over the list of areas, matching them with substring match. 
  -- if we get match a single area, then return it's ID, otherwise return
  -- 'false' and a message that there are than one are matches
  local returnid, fullareaname
  for area, id in pairs(list) do
    if area:find(areaname, 1, true) then
      if returnid then return false, "more than one area matches" end
      returnid = id; fullareaname = area
    end
  end
  
  return returnid, fullareaname
end

-- sample use:
local id, msg = findAreaID("blahblah")
if id then
  echo("Found a matching ID: " .. id")
elseif not id and msg then
  echo("ID not found; " .. msg)
else
  echo("No areas matched the query.")
end


getAreaRooms

getAreaRooms(area id)

Returns a key-value table with all rooms IDs for a given area ID.

-- using the sample findAreaID() function defined in the getAreaTable() example, 
-- we'll define a function that echo's us a nice list of all rooms in an area with their ID
function echoRoomList(areaname)
  local id, msg = findAreaID(areaname)
  if id then
    local roomlist, endresult = getAreaRooms(id), {}
  
    -- obtain a room list for each of the room IDs we got
    for _, id in ipairs(roomlist) do
      endresult[id] = getRoomName(id)
    end
  
    -- now display something half-decent looking
    cecho(string.format(
      "List of all rooms in %s (%d):\n", msg, table.size(endresult)))

    for roomid, roomname in pairs(endresult) do
      cecho(string.format(
        "%6s: %s\n", roomid, roomname))
    end
  elseif not id and msg then
    echo("ID not found; " .. msg)
  else
    echo("No areas matched the query.")
  end
end


getPath

getPath(roomID from, roomID to)

Returns a boolean true/false if a path between two room IDs is possible. If it is, the global `speedWalkPath` table is set to all of the directions that have to be taken to get there, and the global `speedWalkDir` table is set to all of the roomIDs you'll encounter on the way.

-- check if we can go to a room - if yes, go to it
if getPath(34,155) then
  gotoRoom(155)
else
  echo("\nCan't go there!")
end

roomExists

roomExists(roomID)

Returns a boolean true/false depending if the room with that ID exists (is created) or not.


setExit

setExit(from roomID, to roomID, direction)

Creates a one-way exit from one room to another using a standard direction - which can be either one of n, ne, nw, e, w, s, se, sw, u, d, in, out.

Returns false if the exit creation didn't work.

-- alias pattern: ^exit (\d+) (\w+)$

if setExit(mmp.currentroom, tonumber(matches[2]),matches[3]) then
echo("\nExit set to room:"..matches[2]..", Direction:"..string.upper(matches[3]))
centerview(mmp.currentroom)
else
mmp.echo("Failed to set the exit.") end

This function can also delete exits from a room if you use it like so: setExit(from roomID, -1, direction)

Which will delete an outgoing exit in the specified direction from a room.

-- locate the room on the other end, so we can unlink it from there as well if necessary
local otherroom
if getRoomExits(getRoomExits(mmp.currentroom)[dir])[mmp.ranytolong(dir)] then
  otherroom = getRoomExits(mmp.currentroom)[dir]
end

if setExit(mmp.currentroom, -1, dir) then
  if otherroom then
    if setExit(otherroom, -1, mmp.ranytolong(dir)) then
      mmp.echo(string.format("Deleted the %s exit from %s (%d).",
        dir, getRoomName(mmp.currentroom), mmp.currentroom))
     else mmp.echo("Couldn't delete the incoming exit.") end
  else
    mmp.echo(string.format("Deleted the one-way %s exit from %s (%d).",
      dir, getRoomName(mmp.currentroom), mmp.currentroom))
  end
else
  mmp.echo("Couldn't delete the outgoing exit.")
end

setRoomCoordinates

setRoomCoordinates(roomID, x, y, z)

Sets the given room ID to be at the following coordinates visually on the map, where z is the up/down level.

0,0,0 is the center of the map.

-- alias pattern: ^set rc (-?\d+) (-?\d+) (-?\d+)$
local x,y,z = getRoomCoordinates(previousRoomID)
local dir = matches[2]

if dir == "n" then
	y = y+1
elseif dir == "ne" then
	y = y+1
	x = x+1
elseif dir == "e" then
	x = x+1
elseif dir == "se" then
	y = y-1
	x = x+1
elseif dir == "s" then
	y = y-1
elseif dir == "sw" then
	y = y-1
	x = x-1
elseif dir == "w" then
	x = x-1
elseif dir == "nw" then
	y = y+1
	x = x-1
elseif dir == "u" or dir == "up" then
	z = z+1
elseif dir == "down" then
	z = z-1
end
setRoomCoordinates(roomID,x,y,z)
centerview(roomID)

You can make them relative as well:

-- alias pattern: ^src (\w+)$

local x,y,z = getRoomCoordinates(previousRoomID)
local dir = matches[2]

if dir == "n" then
	y = y+1
elseif dir == "ne" then
	y = y+1
	x = x+1
elseif dir == "e" then
	x = x+1
elseif dir == "se" then
	y = y-1
	x = x+1
elseif dir == "s" then
	y = y-1
elseif dir == "sw" then
	y = y-1
	x = x-1
elseif dir == "w" then
	x = x-1
elseif dir == "nw" then
	y = y+1
	x = x-1
elseif dir == "u" or dir == "up" then
	z = z+1
elseif dir == "down" then
	z = z-1
end
setRoomCoordinates(roomID,x,y,z)
centerview(roomID)

getRoomCoordinates

x,y,z = getRoomCoordinates(room ID)

Returns the room coordinates of the given room ID.

local x,y,z = getRoomCoordinates(roomID)
echo("Room Coordinates for "..roomID..":")
echo("\n     X:"..x)
echo("\n     Y:"..y)
echo("\n     Z:"..z)

Miscellaneous Functions