User:CephHunter/Lua guide/Library functions

From the RuneScape Wiki, the wiki for all things RuneScape
Jump to: navigation, search

This part is dedicated in showing examples for how to use most of the standard library functions. For a guide on how to use lua see User:CephHunter/Lua guide instead.

The core lua library and the Scribunto library have a large amount of functions to use. Here, we'll only cover notable uses of them. See the documentation for full details.

In all below descriptions, optional arguments have square brackets around them with default values after a pipe, if appropriate. i.e. foo( x, [y|1] ) means function foo has one required argument, and the second argument is optional and will default to 1.

Contents

Helper modules[edit | edit source]

Helper modules are small user written libraries to help you with common tasks. A full list can be found at RuneScape:Lua/Helper modules.

ModuleFunctionUseExample

Module:Addcommas

Addcommas

_add

_add( num )
Returns a string with num formatted with commas. Also works on ranges of numbers; e.g. '10000-100000' -> '10,000-100,000'
local commas = require('Module:Addcommas')
mw.log(commas._add(100000)) --> '100,000'
mw.log(commas._strip('100,000')) --> '100000'

_strip

_strip( num )
Returns a string with all commas removed from num.

Module:Average drop value

Average drop value

getVal

getVal(mob, parse, rdt)
Returns the average drop value for drops from mob, where mob should be a monster or its version eg Chaos Elemental#P2P. parse, when passed a truthy, attempts to parse text drop rarities (eg common, uncommon etc). rdt, when passed a truthy, adds the average drop value from the rare drop table to the total drop value (assuming 1/1024 chance or rolling rdt).

Module:Chart data

Chart data

_main

_main( args )
Turns a table/chart object into a json string.
local p = {}
local chart = require( 'Module:Chart data' )

-- This chart can then be added to a page using {{Chart data|<module name>|pie}} or {{#Invoke:<module name>|pie}}
-- It could also further be used be another module/function
function p.pie()
    local plot = chart.newChart{ type = 'pie' }
    plot:setDimensions( '40vw', nil, 400, nil, true ) -- Pie chart is always square
    plot.colorPallet = chart.colorPallets.green
    local labels = {}
    local set = plot:newDataSet()

    for i = 1, 6 do
        set:addDataPoint( math.floor( math.sqrt( i ) * 10 + 0.5 ) / 10 )
        table.insert( labels, 'Value ' .. i )
    end

    plot:addDataLabels( labels )

    return plot
end

return p

-------------------------------------------------------------
local p = {}
local chart = require( 'Module:Chart data' )

function p.bar()
    local plot = chart.newChart{ type = 'bar' }
        :setDimensions( '40%', 600, 400, 400, true ) -- Settings can be chained
        :setXLabel( 'x axis label' )
        :setYLabel( 'y axis label' )

    for i = 1, 2 do
        local set = plot:newDataSet()
        for j = 1, 6 do
            set:addDataPoint( math.sqrt( i*j ) )
        end
        set.label = 'Set ' .. i

        if i == 1 then
            set.color = chart.colorPallets.green[3]
        else
            set.color = chart.colorPallets.orange[3]
        end
    end

    local labels = {}

    for i = 1, 6 do
        table.insert( labels, 'Value ' .. i )
    end

    plot:addDataLabels( labels )

    return 'Some header text' .. plot -- Charts are automatically converted to strings when appended to another string
end

return p

convertToXYFormat

convertToXYFormat( ys, [xs|{}] )
Converts the ys array into an array of {x = n, y = y[n]} tables. If xs is already partially filled it will use {x = x[n], y = y[n]} until all values in xs are used, then it will use {x = n, y = y[n]} again for the remaining values in ys.

generateXYFromFunc

generateXYFromFunc( func, start_x, end_x, [step|1] )
Returns an arry of {x = n, y = fun(n)} tables where n ranges from start_x to end_x in step increments. Be careful when using decimal step values as floating point error can cause the generator to stop one element too soon.

jagexInterpolation

jagexInterpolation( low_chance, high_chance, start_level, end_level )

newChart

newChart( [options] )
Returns a new chart object. options is a table with options in the Chart.js format. Most options will be set automatically or will be set later with other functions if not already defined. Usually all you need to define here is the chart type e.g. newChart{ type = 'scatter' }. Check the modules documentation for more info.

chart:addDataSets

chart:addDataSets( ... )
Appends all given data sets to the chart.data.datasets table.

chart:addDataLabels

chart:addDataLabels( labels )
Appends all items in labels to the chart.data.labels table.

chart:setDimensions

chart:setDimensions( width, [height|width], [minWidth|400], [minHeight|400], [resizable|true] )
Sets the dimensions of the chart. If a number is given to width, height, minWidth and minHeight it will be assumed you meant pixels. You can also use strings like 100% to fill the available space, 60vw/60vh to dynamically scale the simensions to the viewport size (i.e. 60vw = 60% of browser's window width). If resizable is true, the chart can be dragged by the lower right corner to change its size. If this function is not called the default values are width = 60vw, height = 60vh, minWidth = 400px, minHeight = 400px and resizable = true.

chart:setTitle

chart:setTitle( [text|nil], [position|'top'] )
Sets the label title of the chart. A value of nil will remove the current title.

chart:setXLabel

chart:setXLabel( [label|nil] )
Sets the label for the x axis. Only works on chart types 'line', 'bar', 'bubble' and 'scatter'. If used without arguments it will remove the current label.

chart:setYLabel

chart:setYLabel( [label|nil] )
Sets the label for the y axis. Only works on chart types 'line', 'bar', 'bubble' and 'scatter'. If used without arguments it will remove the current label.

chart:setXLimits

chart:setXLimits( [min|nil], [max|nil], [step|nil] )
Sets the start, stop and step size of the x axis. Any argument with a value of nil will remove that setting. Only works on chart types 'bubble' and 'scatter'.

chart:setYLimits

chart:setYLimits( [min|nil], [max|nil], [step|nil] )
Sets the start, stop and step size of the y axis. Any argument with a value of nil will remove that setting. Only works on chart types 'line', 'bar', 'bubble' and 'scatter'.

chart:setRadialLimits

chart:setRadialLimits( [min|nil], [max|nil], [step|nil] )
Sets the start, stop and step size of the r axis on polar plots. Any argument with a value of nil will remove that setting. Only works on chart types 'radar' and 'polarArea'.

chart:setXAxisType

chart:setXAxisType( [type|nil] )
Sets the axis type. Supported values are 'linear', 'logarithmic', 'category' and 'time'. If called without arguments it will reset back to the default value 'linear'. Only works on chart types 'bar', 'bubble', 'line' and 'scatter'.

chart:setYAxisType

chart:setYAxisType( [type|nil] )
Same as chart:setXAxisType() but for the y axis. Only works on chart types 'bar', 'bubble', 'line' and 'scatter'.

chart:showLegend

chart:showLegend( val )
Hides the legend if val is false.

chart:setOptions

chart:setOptions( options )
Sets options using Chart.js format but makes sure you only change the given settings and not accidentally delete already existing settings. i.e. using chart:setOptions{ scales = {x = {max = 100}} } while {scales = {x = {min = 0}}} already exists will result in {scales = {x = {min = 0, max = 100}}}.

chart:flipXY

chart:flipXY()
Turn the bar chart into a horizontal one. Only has an effect on bar charts.

chart:debug

chart:debug()
Pretty prints the internal structure since you can't use mw.logObject to do so.

chart:newDataSet

chart:newDataSet( [options] )
Returns a new dataSet object which is also automatically added to the chart datasets table.

dataSet:addData

dataSet:addData( data )
Appends the values of data to the already existing data stored in the dataSet.data array. Using dataset.data = data will overwrite any stored data.

dataSet:addDataPoint

dataSet:addDataPoint( data )
Append a single value to the dataSet.data array. Same as table.insert( dataSet.data, data ).

dataSet:setOptions

dataSet:setOptions( options )
Sets options using Chart.js format.

dataSet:done

dataSet:done()
Returns the parent chart object again.

Module:Clean image

Clean image

clean

clean{ file = [string|'no'], width = [string|nil], height = [string|nil], link = [string|nil], align = [string|nil] }
Used to clean up user input; extracts only the file name of the input and returns its own formatted link.

Input is a table with fields:

  • file - the full wikitext to be cleaned. All processing is skipped if file is empty or is the string no.
  • width - width to resize the file to; no default
  • height - height to resize the file to, can be combined with width; no default
  • link - what page to link the file to; no default (file will link to file page), no to link to nothing
  • align - alignment for the image; left, center, right; no default
local cleanImage = require( 'Module:Clean image' ).clean
mw.log( cleanImage{ file = '[[File:Rune dagger.png|link=Rune dagger|200px]]' } ) --> '[[File:Rune dagger.png|frameless]]'

Module:Coins image

Coins image
( num )Returns a string with the correct coins image name for the absolute value of num. If num is a comma separated string, the highest value in the list will be used for the image.
local coinsImage = require( 'Module:Coins image' )
mw.log( coinsImage( 300 ) ) --> 'Coins_250.png'
mw.log( coinsImage( -300 ) ) --> 'Coins_250.png'
mw.log( coinsImage( '10, 300, 1000' ) ) --> 'Coins_1000.png'

Module:Component costs

Component costs

_main

_main(comp)
Returns the price (and reasoning) for an invention material as an object in the format:

	['price'] = int,
    ['note'] = string

The material name can either be the short or full form and capitalisation doesn't matter.
local compcost = require( 'Module:Component costs' )

local a = compcost._main( 'Refined components' )
mw.logObject( a )
--[=[
table#1 {
  ["note"] = "Based on the price of [[Junk refiner]] (assumes production of 20 components)",
  ["price"] = 1123.7,
}
--]=]

mw.log( compcost._price( 'Protective components' ) --> 33030.3
mw.log( compcost._price( 'protective' ) --> 33030.3

_price

_price(comp)
Returns the price for an invention material as a number. The material name can either be the short or full form and capitalisation doesn't matter.

Module:Currency Image

Currency Image
( name, quantity )Returns the correct currency image name for the number.
  • name is the case insensitive currency name.
  • quantity is a number, or comma-separated string of numbers, the maximum of which will be used.
Supported currency names are: Agility arena tickets, Archery tickets, Beans, Chimes, Coins, Chronotes, Dungeoneering tokens, Ecto-tokens, Pieces of eight, Postage stamps, Runecoins, Runecrafting guild tokens, Rusty coins, Tarddian crystals, Teci, Tokkul, Trading sticks, Urchin points, Vinesweeper points, Zemomark
local currencyImage = require( 'Module:Currency Image' )
mw.log( currencyImage( 'Coins', 300 ) ) --> 'Coins_250.png'
mw.log( currencyImage( 'Runecoins', -300 ) ) --> 'Runecoin.png'
mw.log( currencyImage( 'Zemomark', '10, 300, 1000' ) ) --> 'Zemomark_1000.png'

Module:Currency short

Currency short

_amount

_amount( amount, coinType, [precise|false] )
Returns a string with the correct currency image followed by a formatted and colour coded amount.
  • amount - number to format.
  • coinType - type of image to use.
  • precise - don't shorten amount to k or M if precise = true. Default is false.
Current supported coin types are chimes, coins, rusty, and zemomarks.
local currency = require( 'Module:Currency short' )._amount
mw.log( currency( 10000, 'coins' ) ) --> '<span class="coins coins-10000 coins-pos">10,000</span>'
mw.log( currency( 100000, 'rusty' ) ) --> '<span class="coins rusty-coins-10000 coins-pos">100<b>k</b></span>'
mw.log( currency( -100000, 'rusty', true ) ) --> '<span class="coins rusty-coins-10000 coins-neg">-100,000</span>'

Module:Currency

Currency

_amount

_amount( amount, type )
Returns a string with amount colour coded and formatted with commas and an image of type type in front of it.

Current supported coin types are chimes, coins, nocoins, nocoinsc, rusty, and zemomarks.

nocoins has no image in front and nocoinsc adds the text 'coins' after the number.
local currency = require( 'Module:Currency' )._amount
mw.log( currency( 10000, 'coins' ) ) --> '<span class="coins inventory-image coins-10000 coins-pos">10,000</span>'
mw.log( currency( -10000, 'nocoins' ) ) --> '<span class="coins  coins-neg">-10,000</span>'
mw.log( currency( 0, 'nocoinsc' ) ) --> '<span class="coins ">0 coins</span>'

local coins = require( 'Module:Currency' )._coins
mw.log( coins( 10000) ) --> '<span class="coins inventory-image coins-10000 coins-pos">10,000</span>'

_coins

_coins( amount )
Returns a string with amount colour coded and formatted with commas and an image coins in front of it.

Module:DPL scroll

DPL scroll

_main

_main{ total = [number|0], count = [number|500], offset = [number|0], query = [string/table|{}] }
Generates pagination for usage in DPL headers; see Template:Extension DPL scroll for template version. Table of attributes may include:
  • total - The total number of results
  • count - The number of results per page
  • offset - The current offset
  • query - Additional URL query to add; either:
    • a table of param = value primitive pairs (both strings or numbers; don't nest tables) - the better option for when using this in another module
    • a string of form param1=value1&value2=param2...etc - can (but doesn't need to) start with & or ?
Returns boolean, html where the boolean is true if there is more than one page, false otherwise, and a mw.html object of a span containing the html of the page links (or the empty string if one/no page).

Module:DPLlua

DPLlua

ask

ask( ... )
ask takes a series of tables each containing the settings for a DPL query; it will return the same number of result tables as input tables. All formatting settings are stripped from the config. If the config does not contain include, the result will be a simple list of page names.
❴
	<pagename#1>,
	<pagename#2>,
	<pagename#3>,
❵

A query with an include of the form include = '{template#1}:1:2:param1:param2, {template#2}:3:param1, %0' will give a result like

❴
	['include'] = ❴
		['template#1'] = ❴
			[1] = val#1,
			[2] = val#2,
			['param1'] = val#3,
			['param2'] = val#4,
		❵,
		['template#2'] = ❴
			[3] = val#5,
			['param1'] = val#6,
		❵,
		['%0'] = val#7
	❵,
	['title'] = <pagename>
❵

You can also do include = '{some template}' which will include all parameters of that template in their unexpanded form (templates are not expanded but some content in parser tags is placed in strip markers).

If a template appears multiple times on the same page then that page will appear multiple times in the returned list where each appearance corresponds with an different occurrence of the template on that page. This behaviour can be changes by adding groupMultiTemplateResults = true to the dpl config which results in for example val#1 of the above example will be be a table like {val#1 of template 1, val#1 of template 2, ...}, etc.

If the config value count is larger than 500 it will automatically generate multiple DPL queries with offsets and their outputs will be combined in the returned result.

If the DPL throws an error it will be available in the error field of the output.

Differences with normal DPL:

  • All formatting options are ignored
  • Using include = '{template}' will include all the arguments of that template instead of expanding the template
  • The parameter count can go higher than 500
  • A new option groupMultiTemplateResults is added.
  • When the value of a parameter is a table it will be expanded into multiple lines. E.g. doing notcategory = {val#1, val#2} will expand into
§notcategory = val#1
§notcategory = val#2
Note, if you include a whole template (e.g. include = '{some template}'), content inside strip markers (not nowiki) can't be cleaned up inside lua so pipe characters (|) will be replaced with
local dpl = require( 'Module:DPLlua' )

local a, b = dpl.ask( {
	    namespace = 'Module',
	    linksto = 'Module:Chart data',
	    distinct = 'strict',
	    ordermethod = 'title',
	    nottitlematch = '%/doc|%sandbox%|Exchange/%|Exchange historical/%|Chart data',
	    ignorecase = true
	},{
		namespace = '',
		ignorecase = 'true',
		uses = 'Template:Infobox Recipe',
		count = 1,
		include = '{Infobox Recipe}, {Infobox Item}'
	} )
mw.logObject( a )
mw.logObject( b )
--[=[
table#1 {
  "Module:Chart data/test chart",
  "Module:Chart data/xp chart",
  "Module:Drop rate calculator",
  "Module:Enum",
  "Module:LibraryUtil",
  "Module:Paramtest",
  "Module:Rgba",
  ["DPL time"] = 0.0206,
  ["Parse time"] = 0.0002,
}
table#1 {
  table#2 {
    ["include"] = table#3 {
      ["Infobox Item"] = table#4 {
        ["destroy"] = "Drop",
        ["disassembly"] = "N/A",
        ["equipable"] = "No",
        ["examine"] = "A decorated rune mace.",
        ["id"] = "46698",
        ["image"] = "[[File:Rune burial mace.png]]",
        ["kept"] = "reclaimable",
        ["members"] = "No",
        ["name"] = "Rune burial mace",
        ["quest"] = "No",
        ["release"] = "[[7 January]] [[2019]]",
        ["stackable"] = "No",
        ["tradeable"] = "No",
        ["update"] = "Mining and Smithing Rework",
        ["value"] = "1",
        ["weight"] = "0.04",
      },
      ["Infobox Recipe"] = table#5 {
        ["geValue"] = "no",
        ["level"] = "50",
        ["mat1"] = "Rune mace + 3",
        ["mat1price"] = "gemw",
        ["mat1qty"] = "1",
        ["members"] = "No",
        ["misc1"] = "You must use a [[burial Anvil]] or [[burial Forge|Forge]]",
        ["name"] = "Rune burial mace",
        ["skill"] = "smithing",
        ["skillXP"] = "960.0",
        ["ticks"] = "varies",
        ["ticksnote"] = "See [[Smithing#Forging_items|smithing page]] for details.",
      },
    },
    ["title"] = "Rune burial mace",
  },
  ["DPL time"] = 0.0206,
  ["Parse time"] = 0.00059,
}
]=]

Module:Edit button

Edit button
( [text|'edit'] )Creates an edit button for the current page that the module is invoked on

text defaults to "edit"
local editBtn = require( 'Module:Edit button' )
mw.log( editBtn( 'Click to edit' ) ) --> [//runescape.wiki/w/Rune_dagger?action=edit Click to edit]

-- If used a lot without any text, it's better to do this
local editBtn = require( 'Module:Edit button' )() -- Only store the returned text
mw.log( editBtn ) --> [//runescape.wiki/w/Rune_dagger?action=edit edit]

Module:Enum

Enum

all

all( enum, [fn], [clone|false] )
Loops over the array part of enum and passes each element as the first argument to fn. If fn returns true for all elements then all() returns true, otherwise false. If no function is given function( item ) return item end is used.
local enum = require( 'Module:Enum' )

local seqOne = {1, 2, 3, 4, 10}
local seqTwo = {'a', 'b', 'b', 1}
local seqThree = {}
local var, var2

enum.any( seqOne, function( item ) return item == 3 end ) --> true
enum.all( seqTwo, function( item ) return type( item ) == 'string' end ) --> false
enum.each( seqOne, function( item ) table.insert( seqThree, item * 2 ) end ) --> seqThree = {2, 4, 6, 8, 20}
seqThree = enum.map( seqOne, function( item ) return item * 2 end ) --> seqThree = {2, 4, 6, 8, 20}
seqThree = enum.filter( seqTwo, function( item ) return type( item ) == 'string' end ) --> seqThree = {'a', 'b', 'b'}
seqThree = enum.reject( seqTwo, function( item ) return type( item ) == 'string' end ) --> seqThree = {1}
var = enum.find( seqOne, function( item ) return item > 5 end ) --> var = 10
var = enum.find_index( seqTwo, function( item ) return type( item ) ~= 'string' end ) --> var = 4
var, var2 = enum.max_by( seqOne, function( item ) return (item % 10) * item end ) --> var = 4, var2 = 16
var = enum.reduce( seqOne, function( item, acc ) return acc + item*item end, 5 ) --> var = 135
var = enum.range( 10, 1, -3 ) --> var = {10, 7, 4, 1}
seqThree = enum.scan( seqOne, function( item, acc ) return acc + item*item end, 5 ) --> seqThree = {6, 10, 19, 35, 135}
seqThree = enum.slice( seqOne, 2, 4 ) --> seqThree = {2, 3, 4}
var, var2 = enum.split( seqOne, 2 ) --> var = {1, 2}, var2 = {3, 4, 10}
var = enum.sum( seqOne ) --> var = 20
seqThree = enum.take( seqOne, 2 ) --> seqThree = {1, 2}
seqThree = enum.take_every( seqOne, 2 ) --> seqThree = {1, 3, 10}
seqThree = enum.unique( seqTwo ) --> seqThree = {'a', 'b', 1}
seqThree = enum.zip( {seqOne, seqTwo, {20, 30}} ) --> seqThree = {{1, 'a', 20}, {2, 'b', 30}, {3, 'b'}, {4, 1}, {10}}
seqThree = enum.insert( seqOne, seqTwo, 3 ) --> seqThree = {1, 2, 'a', 'b', 'b', 1, 3, 4, 10}
seqThree = enum.intersect( seqOne, seqTwo ) --> seqThree = {1}
var = enum.intersects( seqOne, seqTwo ) --> var = true
cond = enum.contains({ 1, 2, 3}, 3) --> cond = true

inc = enum.newIncrementor( 10, 5 )
print( inc() ) --> 10
print( inc() ) --> 15

-- Reason to use clone:
seqOne = {{1}, {2}}
seqTwo = enum.slice( seqOne, 2, 2 ) --> seqTwo = {{2}}
seqTwo[1][1] = 5
mw.log( seqOne[2][1] ) --> 5, The value in seqOne also got changed

seqOne = {{1}, {2}}
seqThree = enum.slice( seqOne, 2, 2, true ) --> seqThree = {{2}}
seqThree[1][1] = 5
mw.log( seqOne[2][1] ) --> 2, The value in seqOne is unchanged

any

any( enum, [fn], [clone|false] )
Loops over the array part of enum and passes each element as the first argument to fn. If fn returns true for at least one element then any() returns true, otherwise false. If no function is given function( item ) return item end is used. If clone is true the input enum is deep copied using mw.clone() before use.

contains

contains( enum, elem, [clone|false] )
Returns true if enum contains elem, otherwise returns false.

each

each( enum, fn, [clone|false] )
Loops over the array part of enum and passes each element as the first argument to fn. This function returns nothing.

filter

filter( enum, [fn], [clone|false] )
Loops over the array part of enum and passes each element as the first argument to fn. If fn returns true the corresponding element is copied to a new table which is then returned. If no function is given function( item ) return item end is used.

find

find( enum, fn, [default|nil], [clone|false] )
Loops over the array part of enum and passes each element as the first argument to fn. The first element where fn returns true is returned. If no elements passes the test, default is returned.

find_index

find_index( enum, fn, [default|nil], [clone|false] )
Loops over the array part of enum and passes each element as the first argument to fn. The index of the first element where fn returns true is returned. If no elements passes the test, default is returned.

insert

insert( enum1, enum2, [index|#enum1+1], [clone|false] )
Returns a new table with enum2 inserted into enum1 at index index. If no index is given, enum2 is appended to enum1.

intersect

intersect( enum1, enum2, [clone|false] )
Returns a table containing elements which exist in both enums. The order of the elements is the same as the order they occure in enum1.

intersects

intersects( enum1, enum2, [clone|false] )
Returns true if both sets have at least one element with equal values.

map

map( enum, fn, [clone|false] )
Loops over the array part of enum and passes each element as the first argument to fn. The return value of fn is appended to a new table. This new table is returned.

max_by

max_by( enum, fn, [clone|false] )
Loops over the array part of enum and passes each element as the first argument to fn. max_by() returns two values, the first is the element where fn returned the largest value, the second is this largest value. The > operator is used for the comparisons.

new

new( [enum|{}] )
Adds a metatable to enum which allows it use elementwise math operations on the table. Also makes it possible to use the colon : operator with all the other functions listed here that take a table as their first argument.
local t = enum.new1, 2, 3
local t2 = enum4, 5, 6 -- Alternative notation

mw.log( -t ) --> ❴ -1, -2, -3 ❵
mw.log( t + 2 ) --> ❴ 3, 4, 5 ❵
mw.log( t - 2 ) --> ❴ -1, 0, 1 ❵
mw.log( t * 2 ) --> ❴ 2, 4, 6 ❵
mw.log( t / 2 ) --> ❴ 0.5, 1, 1.5 ❵
mw.log( t ^ 2 ) --> ❴ 1, 4, 9 ❵

mw.log( t + t2 ) --> ❴ 5, 7, 9 ❵
mw.log( t .. t2 ) --> ❴ 1, 2, 3, 4, 5, 6 ❵
mw.log( t:sum() ) --> 6
mw.log( (t .. t2):reject3, 4, 5 ) --> ❴ 1, 2, 6 ❵

newIncrementor

newIncrementor( [start|1], [step|1] )
Returns a new incrementor function. Every time this incrementor function is called it returns a number step higher than the previous call. The current value can be obtained with inc.n or set inc.n = number where inc is an incrementor function. The step size can be changed with inc.step = number.

range

range( stop )
range( start, stop, [step|1] )
Returns a table containing a sequence of numbers from start to stop (both inclusive if ints, end-exclusive if floats) by step. range(4) produces {1, 2, 3, 4} (start defaults to 1). range(0, 4) produces {0, 1, 2, 3, 4}. When step is given, it specifies the increment (or decrement).

reduce

reduce( enum, fn, [accumulator|enum[1]], [clone|false] )
Loops over the array part of enum and passes each element as the first argument and accumulator as the second to fn. The return value of fn becomes the new accumulator. The final value of accumulator is returned. If no accumulator is given then the first element in enum is used.

reject

reject( enum, [fn], [clone|false] )
reject( enum, [table], [clone|false] )
The opposite of filter(). If the second argument is a table, every element in enum equal to any of the values in this table will be rejected.

rep

rep( val, n, [clone|false] )
Returns a table with n copies of val.

scan

scan( enum, fn, [accumulator|enum[1]], [clone|false] )
Same as reduce() but each step is appended to a table. This table is then returned.

slice

slice( enum, [start|1], [stop|#enum], [clone|false] )
Returns a table containing all the elements of enum between the start and stop indices. The start and stop indices are inclusive.

split

split( enum, count, [clone|false] )
Returns two tables where the first is equivalent to slice( enum, 1, count ) and the second slice( enum, count+1, #enum ).

sum

sum( enum, [clone|false] )
Returns the sum of all array elements in enum.

take

take( enum, count, [clone|false] )
Returns only the first table of split( enum, count ).

take_every

take_every( enum, n, [clone|false] )
Returns a table containing every nth element of enum.

unique

unique( enum, [fn], [clone|false] )
Returns a new table where all duplicate values in enum are removed. In case a duplicate is present, the element with the lowest index will be kept and every subsequent duplicate element is removed. fn can be used to create a custom id for every element so that the result is a table with elements which all create a unique id. If no function is given function( item ) return item end is used.

zip

zip( enums, [clone|false] )
Groups elements with the same indexes from different arrays together, i.e. zip{ {a1, a2, a3}, {b1, b2, b3}, {c1, c2} } -> {{a1, b1, c1}, {a2, b2, c2}, {a3, b3}}

Module:ExchangeLite

ExchangeLite

load

load{ item = string, dataType = string }
Lightweight version of Module:Exchange. Returns the data type requested for the specified item. Any of the fields of an exchange page can be used (see Module:Exchange/Fire rune)
local exchange = require( 'Module:ExchangeLite' )
mw.log( exchange.load{ item = 'Rune dagger', dataType = 'limit' } ) --> 100
mw.log( exchange.price( 'Rune dagger' ) ) --> 9684

price

price( item )
Returns the Grand exchage price of item as a number.

Module:Experience

Experience

_xp_at_level

_xp_at_level(level, [isElite|false])
Returns lowest needed XP to have required level.

_xp_at_level_unr

_xp_at_level_unr(level, [isElite|false])
Same as above, but with the 120/150 level cap removed.

_max_xp_at_level

_max_xp_at_level(level, [isElite|false])
The maximum amount of experience you can have at a given level.

_level_at_xp

_level_at_xp(xp, [isElite|false])
What level you have when at a given xp.

_level_at_xp_unr

_level_at_xp_unr(xp, [isElite|false])
Same as above, but with the 120/150 level cap removed.

_xp_to_level

_xp_to_level(xp, target, [isElite|false])
Experience needed to obtain a level from a given amount of xp. If current xp is greater than target, returns 0.

_level_to_level

_level_to_level(level1, level2, [isElite|false])
Experience between two levels; will always return absolute value.

_level_to_level_unr

_level_to_level_unr(level1, level2, [isElite|false])
Same as above, but with the 120/150 level cap removed.

remainingExp

remainingExp(curLvl, curXP, tgtLvl, tgtXP, [isElite|false])
Finds and returns experiences and levels based on inputs. Returns 5 values: current level, current experience, goal level, goal experience, experience remaining.

Module:Iterator

Iterator

opairs

opairs( t )
Does the same as pairs() but makes sure it iterates in alphabetical order; numbers come before letters.
local it = require( "Module:Iterator" )

local t = {
    a = 'string 1',
    d = 'string 2',
    b = 'string 3',
    4,
    6,
    5
}

for key, value in it.opairs( t ) do
    mw.log( 'key: ' .. key .. '; value: ' .. value )
end
-- key: 1; value: 4
-- key: 2; value: 6
-- key: 3; value: 5
-- key: a; value: string 1
-- key: b; value: string 3
-- key: d; value: string 2


local t2 = {
    a = 5,
    b = 4,
    c = 20,
    d = 1
}

for i, key, value in it.sortedPairs( t2, function(lhs, rhs) return lhs < rhs end ) do
    mw.log( 'i: ' .. i .. '; key: ' .. key .. '; value: ' .. value )
end
-- i: 1; key: d; value: 1
-- i: 2; key: b; value: 4
-- i: 3; key: a; value: 5
-- i: 4; key: c; value: 20

spairs

spairs( t )
Inverse of ipairs(); only iterates over keys that are of the type string.

ospairs

ospairs( t )
Same as spairs() but iterates in alphabetical order.

sortedPairs

sortedPairs( t, func )
Iterates over all elements of t in the order defined by the sort function. The iterator returns three values, the current itertation index (like ipairs), the original key of the item and the value of the item.

Module:Lazyload

Lazyload

genLink

genLink(file, opts)
Generates a link to load a file on click.
  • file is the file name to be loaded (without the File: but with file extension), for example Lazy Guard.png
  • opts (optional) a table of other options, those being:
    • disp Text to display instead of Load File name.png
    • alt Custom alt text for the loaded image
    • class Custom class to add to loaded image
    • size A pixel size for the image. (Equivalent to [[Image.png|100px]])
    • thumb Use thumbnail style for the image, any value works. (Equivalent to [[Image.png|thumb]])
JS and CSS are contained at MediaWiki:Gadget-lazyload-core.js and MediaWiki:Gadget-lazyload-core.css respectively.
local lazyload = require( 'Module:Lazyload' )
mw.log( lazyload.genLink('Lazy Guard.png', {disp='Load image of a lazy guard', alt='lazy guards image', class='custom-class', size='100', thumb='t'}) ) --> '<span class="rsw-lazyload" data-file="/images/thumb/d/d9/Lazy_Guard.png/100px-Lazy_Guard.png?420a7?ll23" data-alt="lazy guards image" data-class="custom-class thumbimage">[[:File:Lazy Guard.png|Load image of a lazy guard]]</span>'
mw.log( lazyload.allLink('Load all these images') ) --> '<span class="rsw-lazyload-all">[[#|Load all these images]]</span>'

allLink

allLink(text)
Generates a link to load all images on a page. text is the text to display as the link (optional), default is Load all images JS and CSS are contained at MediaWiki:Gadget-lazyload-core.js and MediaWiki:Gadget-lazyload-core.css respectively.

Module:Logger

Logger

log

log(table)
Deprecated: usemw.logObject(obj) instead.

Logs the contents of the table to the console (does not expand subtables).

Notes:

  • Assumes all table indices can be represented as strings - using functions or tables as indices will result in non-specific log entries
  • This is best used by adding p.logger = require('Module:Logger') to the top of the module, then calling p.logger.log(obj) in the debug console on the module page
  • This module will only print to the debug console - it has no use when used outside of the development environment and should be removed/commented out before saving
local logger = require('Module:Logger')

local t1 = { 1, 2, 3, 4 }
local t2 = { 1, 2, 3, a='a' }
local t3 = { a='a', b='b' }
local t4 = { a=t1, b=t1, t2, t3 }
local t5 = { 1, 2, 3, '4444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444' }
local t6 = { '1', '2', a={'12'} }

mw.log( p.dumpObject(t1) )
logger.logCleanTable(t2)
logger.logCleanTable(t3)
logger.logCleanTable(t4, { collapseLimit=60 })
logger.logCleanTable(t5)
logger.logObject(t6)
-- table#1 (#=4, n=4) {
--   1,
--   2,
--   3,
--   4,
-- }
-- { 1, 2, 3, a="a" }
-- { a="a", b="b" }
-- {
--     { 1, 2, 3, a="a" },
--     { a="a", b="b" },
--     a = { 1, 2, 3, 4 },
--     b = { 1, 2, 3, 4 },
-- }
-- {
--     1,
--     2,
--     3,
--     "4444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444",
-- }
-- table#1 (#=2, n=3) {
--   "1",
--   "2",
--   ["a"] = table#2 (#=1, n=1) {
--     "12",
--   },
-- }

deep_log

deep_log(table)
Deprecated: usemw.logObject(obj) instead. Logs the contents of the table to the console, expanding subtables. See above notes.

dumpObject

dumpObject(table, options)
Modified version of mw.dumpObject. Default values of the options are:
  • clean = false;     Removes the table#n and expands all tables even if the same table appears multiple times. The output is safe to load again by lua without further processing. Does not work for circular dependencies.
  • indentSize = 2;     Number of spaces/tabs to add for each indent level.
  • useTabs = false;     Use tabs to indent instead of spaces.
  • tabSize = 4;     Used to calculate the collapseLimit.
  • collapseLimit = 0;     Maximum length for collapsing a table onto a single line.
  • collapseArrays = true;     Allow arrays to collapse onto a single line.
  • wrapLongArrays = false;     Keep arrays collapsed and simply continue on a new line if the current line is longer then collapseLimit.
  • collapseObjects = true;     Allow key-value pairs to collapse onto a single line.
  • addEqualSignSpaces = false;     Add spaces around equal signes when the table is collapsed. Non collapsed table always have spaces.
  • addBracketSpaces = true;     Add spaces between the brackets and the data for collapsed tables i.e. { 'data' }.
  • numberPrecision = -1;     Number of decimals. Trailing zeros are trimmed. Negative numbers means let lua decide.

logObject

logObject(table, options)
Uses dumpObject and prints its result to the console.

logCleanTable

logCleanTable(table, options)
Uses dumpObject and prints its results to the console but has the following default options changed:
  • clean = true
  • indentSize = 4
  • collapseLimit = 100
  • collapseArrays = true
  • collapseObjects = true

Module:Mainonly

Mainonly

_main

_main( arg )
If the module is invoked in the content namespace, it will return arg, otherwise, it will return an empty string.
local mainonly = require( 'Module:Mainonly' )

-- If used on an invoke coming from e.g. [[Weird gloop]]
mw.log( mainonly._main( 'some text' ) ) --> 'some text'
mw.log( mainonly.on_main() ) --> true

-- If used on an invoke coming from e.g. [[User:Weird gloop]] or [[Template:Weird gloop]]
mw.log( mainonly._main( 'some text' ) ) --> ''
mw.log( mainonly.on_main() ) --> false

on_main

on_main()
Returns true if invoked in the content namespace, otherwise false

Module:Map coordinates

Map coordinates

convertMap

convertMap(z,x,y)
Converts interactive map coordinates into Runescape camera position coordinates

convertRS

convertRS(z,x1,y1,x2,y2)
Converts Runescape camera position coordinates into interactive map coordinates

convertInt

convertInt(int)
Converts integer coordinates (eg from cache) into interactive map coordinates

convertDegMin

convertDegMin(ns, ndeg, nmin, ew, edeg, emin)
Converts degree and minute coordinates into interactive map coordinates

transform

transform(z,x,y,map)
Converts x,y map position to actual rs3 wiki map position. Not normally needed as it is integrated in the other functions.

Module:Map

Map

parseArgs

parseArgs(args, ptype)
Parses unnamed arguments into points. Returns the arguments given with a pins table and pin_count, x_range, y_range, squareX, squareY if not otherwise specified.
  • Arguments are strings in the format x,y or x:#,y:#,plane:#.... For arguments per pin see Module:Map.
  • ptype is the pin type (used to generate descriptions).
  • createMap

    createMap(args)
    Creates a map or maplink for the args. Returns the preprocessed <maplink> or <map> tag. For poossible arguments see Module:Map.

    featSquare

    featSquare(args, opts)
    Creates the json for a square, to be used within the FeatureCollection json. Args are: {x=#, y=#, [squareX=#], [squareY=#], [r=#], [styles]}. Opts are: {mapID=#, plane=#}.

    featPolygon

    featPolygon(args, opts)
    Generates the json for a single polygon from the given points (to be used within the FeatureCollection json). Args are: {pins={}, [styles]} where pins are {x=#, y=#}. Opts are: {mapID=#, plane=#}.

    featLine

    featLine(args, opts)
    Generates the json for a line from the given points (to be used within the FeatureCollection json). Args are: {pins={}, [close=boolean], [styles]} where pins are {x=#, y=#}. Opts are: {mapID=#, plane=#}.

    featCircle

    featCircle(args, opts)
    Generates the json for a circle (to be used within the FeatureCollection json). Args are: {x=#, y=#, [r=#], [styles]}, opts are: {mapID=#, plane=#}.

    featPin

    featPin(args, opts, pin)
    Generates the json for a single pin (to be used within the FeatureCollection json). Args are: {[styles]}, opts are: {mapID=#, plane=#}, pin is {x=#, y=#, [desc=string]}

    Module:Mw.html extension

    Mw.html extension

    addClassIf

    addClassIf(cond, class)
    If cond = true it behaves the same as the normal addClass function, otherwise it's a no-op. Ex.: mw.html.create('div'):addClassIf(true, 'align-left-1')

    attrIf

    attrIf(cond, name, value)
    Similar to addClassIf

    cssIf

    cssIf(cond, name, value)
    Similar to addClassIf

    doneIf

    doneIf(cond)
    Similar to addClassIf

    tagIf

    tagIf(cond, tag)
    Similar to addClassIf

    wikitextIf

    wikitextIf(cond, text)
    Similar to addClassIf

    na

    na()
    Shortcut for :tag('td'):attr('data-sort-value', 0):attr('class','table-na'):wikitext('<small>N/A</small>'):done()

    naIf

    naIf(cond)
    Similar to addClassIf

    tr

    tr([settings])
    Shortcut for :tag('tr') but also auto closes the previous 'tr', 'th' or 'td' tag (so you don't need to add :done() before it). settings is a table with keys:
    • class or addClass - A string passed to :addClass()
    • attr - A table passed to :attr()
    • css - A table passed to :css()
    • cssText - A string passed to :cssText()

    th

    th([settings])
    Shortcut for :tag('th'):wikitext(settings) if settings is a string. Also auto closes the previous 'th' or 'td' tag. settings can also be a table with keys:
    • [1] (array) or wikitext - A string passed to :wikitext()
    • class or addClass - A string passed to :addClass()
    • attr - A table passed to :attr()
    • css - A table passed to :css()
    • cssText - A string passed to :cssText()

    td

    td([settings])
    Same as :th(). Example:
    local tbl = mw.html.create('table')
    tbl:tr class='sortable' 
            :th'foo', attr='data-sort-type', 'number'❵❵
            :th('bar')
        :tr()
            :td('buz')
                :attr('data-sort-value', 10)
            :td'N/A', class='table-na'
    

    IF

    IF(cond)
    Allows for if-blocks without breaking the chain. If the condition is true it is a no-op, if false everything inside the balanced IF-END block will be ignored. Can be nested. Ex.:
    mw.html.create('div')
        :IF(true)
            :wikitext('Conditional text')
        :END()
        :...
    

    Note: This only prevents elements from being added to your html object, it does not protect against statements that throw errors. I.e

    mw.html.create('div')
        :IF(false)
            :wikitext(5 * nil) -- This will still throw an error
        :END()
    

    ELSEIF

    ELSEIF(cond)
    Used together with IF().

    ELSE

    ELSE()
    Used together with IF().

    END

    END()
    Used together with IF(). Make sure the IF-END tags are balanced, it wont throw an error if they are not.

    exec

    exec(func, ...)
    Call a function without breaking the chain. See module docs for more info.

    addFunction

    addFunction(func, name)
    Add a function to the mw.html class that can then be used on mw.html object. See module docs for more info.

    Module:Number

    Number

    _round

    _round(num, dp)
    Rounds num to a precision given by dp, if dp is not specified, it defaults to zero.

    _short

    _short(str)
    Convert numbers ending in k, m or b to the actual correct number. Example: 3.5k -> 3500

    Module:Paramtest

    Paramtest

    is_empty

    is_empty(arg)
    Returns true if arg is not defined or contains only whitespace

    has_content

    has_content(arg)
    Returns true if arg exists and does not only contain whitespace

    default_to

    default_to(arg1,arg2)
    If arg1 exists and does not only contain whitespace, the function returns arg1, otherwise returns arg2

    defaults

    defaults{ {arg1,arg2},...}
    Does the same as default_to() run over every table passed; for technical reasons, all nil are replaced with false

    Module:Purge

    Purge

    _purge

    _purge( anchor, text, tag, noinplace )
    Generates a purge link

    All args are optional.

    • anchor - The ID of the tag, used for an anchor link; default res
    • text - Link text; default (wrong?)
    • tag - HTML tag to use; default small
    • noinplace - If defined, will suppress the addition of the jsPurgeLink class, which makes the link do an in-place purge rather than going to a purge confirmation
    local purge = require( 'Module:Purge' )._purge
    
    local refreshLink = purge( nil, 'refresh' )
    -- Or
    local refreshLink = purge{ text = 'refresh' }
    

    Module:Reftag

    Reftag
    {attr}Table of attributes may include:
  • name - A defined name for the ref
  • group - A defined group for the ref
  • text - The text inside the ref tags
  • selfClosing - true or false; whether or not the tag will close itself
  • Module:Rgba

    Rgba

    new

    new( red, [green|0], [blue|0], [alpha|1] )
    new( hex )
    Returns a new rgba object. Values red, green and blue are in the range 0-255; alpha is 0-1. It is also possible to give a hex string e.g. #112233 or #11223344. When converted to a string with tostring( rgba ) it will return a string in the form rgba(r,b,g,a) where r, g, b and a are filled in with numbers.
    local rgba = require( 'Module:Rgba' )
    
    local color1 = rgba.new( 126, 20, 6 )
    mw.log( color1 ) --> 'rgba(126,20,6,1)'
    mw.log( color1:lighten( 1.3 ) ) --> 'rgba(164,26,8,1)'
    mw.log( color1:darken( 1.3 ) ) --> 'rgba(97,15,5,1)'
    mw.log( color1:hueRotate( 50 ) ) --> 'rgba(126,120,6,1)'
    mw.log( color1:saturate( 1.1 ) ) --> 'rgba(132,15,0,1)'
    mw.log( color1:fade( 0.3 ) ) --> 'rgba(126,20,6,0.3)'
    
    local color2 = color1:lighten( 1.3 ):saturate( 1.1 ) -- Operations can be chained
    mw.log( color2 ) --> 'rgba(172,20,0,1)'
    mw.log( color1 ) --> 'rgba(126,20,6,1)' color1 is unchanged
    

    rgba:lighten

    rgba:lighten( val )
    Returns a new rgba object with its brightness changed. 1 is no change, 0 is complete black, 2 is double brightness, 1.1 is 10% more, 0.5 is halve, etc.

    rgba:darken

    rgba:darken( val )
    Returns a new rgba object with its brightness changed. 1 is no change, 0 is complete white, 2 is halve brightness, 1.1 is 10% darker, 0.5 is double brightness, etc.

    rgba:hueRotate

    rgba:hueRotate( num )
    Returns a new rgba object with its hue num degrees rotated. Decimal values are allowed.

    rgba:saturate

    rgba:saturate( val )
    Returns a new rgba object with its saturation changed. 1 is no change, 0 is greyscale, 2 is double saturation, 1.5 is 50% more, etc.

    rgba:fade

    rgba:fade( val )
    Returns a new rgba object with its alpha value set to val. val is clipped to the range 0-1.

    rgba:clone

    rgba:clone()
    Returns a copy with the same values.

    Module:Stable sort

    Stable sort
    (list)Stable sorts the list in-place, using < as the comparison.
    (list, comp)Stable sorts the list in-place, using the provided function as the comparison. The function has two parameters, a and b, and should return true when a is less than b (should come after b in the list).

    Module:Switch infobox

    Switch infobox

    _main

    _main({text1=..., item1=..., ...})
    Generates a switch infobox, following the same format of parameters as the template - though everything should be strings to be compatible with :wikitext()

    Module:Tables

    Tables

    _row

    _row(row, elts, header)
    Adds td or th cells to the html object with the cells data specified by elts. If header = true then all cells added will have the th tag.

    _table

    _table(table, data)
    Adds tr rows and td/th cells to the html object, the data for the rows and cells is specified by data.

    Module:Top icons

    Top icons

    _main

    _main( wiki1, wiki2, ... )
    Returns a string that adds top icons for the given wiki names. Values must be one of rs, rsc, meta or wp.

    _main

    _main( wiki1 = pagename1, wiki2 = pagename2, ... )
    Returns a string that adds top icons for the given wiki names, linking to the specified page names. Wiki names must be one of rs, rsc, meta or wp.

    Module:Translations

    Translations

    _main

    _main(inp, opts)
    Generates a table of translations for the given input inp. Options are passed as a table of key-value pairs, available options are
    • dataType the type of thing being translated, one of item, npc, quest or music. Defaults to item.
    • fuzzy whether the input should be seen as imprecise true or exact false. Defaults to false.
    Returns a table containing the id and all available translations (en, pt, fr, de).
    local trans = require( 'Module:Translations' )
    mw.log( trans._main( 'Bond' ) ) --> <table class="wikitable sortable"><th>ID</th><th>English</th><th>Portuguese</th><th>French</th><th>German</th><tr><td>29492</td><td>Bond</td><td>Nota</td><td>N/A</td><td>N/A</td></tr></table>
    mw.log( trans._simple( 'Bond', 'en', 'item', 'pt') ) --> Nota
    

    _simple

    _simple(inp, lang, dtype, out)
    Returns the requested translation for the given input as a plain string. This looks for exact values.
    • inp the input to look for, based on lang
    • lang the language of the input, one of id, en, pt, fr, or de.
    • dtype the type of the inputm one of item, npc, quest or music.
    • out the desired output language, one of id, en, pt, fr, or de.

    Module:Use strict

    Use strict
    ( [ignoreFunc|nil] )Throws an error if you try to read a non existing global variable or if you try to make a new global variable.

    Allow global functions if ignoreFunc is the string 'ignore functions'.

    Should be placed at the very top of your module before any other require.
    require( 'Module:Use strict' )
    a = 5 --> Lua error in console input at line 8: Attempting to create new global variable "a".
    local a = b --> Lua error in console input at line 9: Attempting to read non existing global variable "b".
    function test() return 0 end --> Lua error in console input at line 10: Attempting to create new global function "test".
    
    --------
    
    require( 'Module:Use strict' )( 'ignore functions' )
    function test() return 0 end
    mw.log( test() ) --> 0
    

    Module:Yesno

    Yesno
    (arg)Reads arg for yes/no and returns the appropriate boolean or nil
    (arg1,arg2)Reads arg1 for yes/no and returns the appropriate boolean; returns arg2 if arg1 was not an applicable value

    Lua library functions[edit | edit source]

    The lua library is the core library of the lua language itself. You can read more about each function in the documentation; this is just a quick summary and does not include all of the functions.

    Basic functions[edit | edit source]

    Functions providing core functionality.

    Function Description Example

    require

    require( modulename )
    Loads the specified module. See #Requiring modules.
    local paramtest = require( 'Module:Paramtest' )
    

    pairs

    pairs( table )
    Returns an iterator function for use in a for-each loop to iterate over all the keys in the array. Order is not specified.
    local t = { a=1, b=3, hello='world' }
    for k, v in pairs( t ) do
      -- block
    end
    

    ipairs

    ipairs( table )
    Returns an iterator function for use in a for-each loop to iterate over all the items in a sequence in numerical order.
    local t = { 'a', 'b', 'hello', 'world' }
    for i, v in ipairs( t ) do
      -- block
    end
    

    pcall

    pcall( f, ... )
    Runs function f in protected mode. If f results in an error, returns false and the error message; otherwise returns true and the normal return values of the function.

    Typically used to check the GE price of something safely, if needed.

    -- returns true, [GE price of an abyssal whip]
    pcall( exg.price, 'Abyssal whip' )
    
    -- returns false, 'package.lua:80: module `Module:Exchange/Foobarbaz' not found'
    pcall( exg.price, 'Foobarbaz' )
    

    type

    type( val )
    Returns the type of val, as a string.
    type( {} ) --> 'table'
    type( 1 ) --> 'number'
    type( '1' ) --> 'string'
    type( type ) --> 'function'
    

    tonumber

    tonumber( val, [base|10] )
    Attempts to convert val into a number with the specified base (2 to 36).
    tonumber( '2' )
    

    tostring

    tostring( val )
    Converts val into its string representation.
    tostring( 2 ) --> '2'
    tostring( {} ) --> 'table'
    tostring( tostring ) --> 'function'
    

    unpack

    unpack( table, [start|1], [stop|#table] )
    Returns the values from the table (sequence) as a comma-separated list suitable for function calls or assignment. i.e., it removes the curly braces from the sequence. Non-sequence behaviour not defined.
    local t = { '1001', 2 }
    local a, b = unpack( t )
    

    setmetatable

    setmetatable( table, metatable )
    Sets the metatable of a table. metatable may be nil, but must be explicitly provided. This will be covered more later.
    local t = { '1001', 2 }
    local mt = {
        __index = function( t, k )  -- This function is called when a non existing key is accessed
            return 0
        end
    }
    setmetatable( t, mt )
    mw.log( t[1] ) --> '1001'
    mw.log( t[5] ) --> 0
    

    getmetatable

    getmetatable( table )
    Returns the metatable of a table. Any other type will return nil.

    Math library[edit | edit source]

    Functions associated with mathematical operations.

    Function Description Example

    math.abs

    math.abs( x )
    Absolute value of x.
    math.abs( 5 ) --> 5
    math.abs( -5 ) --> 5
    

    math.pi

    math.pi
    The number pi.
    math.pi * radius ^ 2
    

    math.sin

    math.sin( x )

    math.cos

    math.cos( x )

    math.tan

    math.tan( x )

    math.asin

    math.asin( x )

    math.acos

    math.acos( x )

    math.atan

    math.atan( x )
    Trigonometric functions of x, in radians.
    math.sin( math.pi )
    

    math.sinh

    math.sinh( x )

    math.cosh

    math.cosh( x )

    math.tanh

    math.tanh( x )
    Hyperbolic functions of x.
    math.sinh( 1 )
    

    math.deg

    math.deg( x )
    Converts x from radians to degrees.
    math.deg( math.pi )
    

    math.rad

    math.rad( x )
    Converts x from degrees to radians.
    math.rad( 90 )
    

    math.floor

    math.floor( x )
    Rounds x down to the next integer (always toward negative infinity)
    math.floor( 3.5 ) --> 3
    math.floor( -3.5 ) --> -4
    

    math.ceil

    math.ceil( x )
    Rounds x up to the next integer (always toward positive infinity)
    math.ceil( 3.5 ) --> 4
    math.ceil( -3.5 ) --> -3
    

    math.exp

    math.exp( x )
    math.exp( 10 )
    

    math.pow

    math.pow( x, y )
    math.pow( 2, 8 )
    

    math.sqrt

    math.sqrt( x )
    math.sqrt( 2 )
    

    math.log

    math.log( x )
    Natural logarithm of x.
    math.log( 10 )
    

    math.log10

    math.log10( x )
    Base-10 logarithm of x.
    math.log10( 10 )
    

    math.max

    math.max( x, ... )
    Returns the maximum value of all the supplied arguments. Behaviour with NaNs is not specified.
    math.max( 1, 4, 6, 10, 99 ) --> 99
    

    math.min

    math.min( x, ... )
    Returns the minimum value of all the supplied arguments. Behaviour with NaNs is not specified.
    math.min( 1, 4, 6, 10, 99 ) --> 1
    

    math.modf

    math.modf( x )
    Returns two values: the integer part of x and the fractional part of x.
    local int, frac = math.modf( 1.25 )
    mw.log( int ) --> 1
    mw.log( frac ) --> 0.25
    

    math.random

    math.random( [x], [y] )
    Generates a psuedorandom number: a real number between 0 (inclusive) and 1 (exclusive); an integer 1 to x (both inclusive); or an integer between x and y (both inclusive) - with 0, 1, or 2 parameters specified respectively.
    math.random( 1, 10 )
    

    math.randomseed

    math.randomseed( x )
    Sets the random seed to x.
    math.randomseed( 1337 )
    

    math.huge

    math.huge
    The value representing positive infinity; larger than or equal to any other numerical value.
    mw.log( math.huge ) --> inf
    

    Operating system library[edit | edit source]

    Functions to do with the operating system's time.

    Function Description Example

    os.clock

    os.clock()
    Approximate number of seconds of CPU time used by the program so far. Has a resolution of 10µs.
    local t1 = os.clock()
    -- code
    local t2 = os.clock()
    mw.log( 'Started at ' .. t1 .. ', finished at ' .. t2 )
    mw.log( 'Duration: ' .. t2 - t1 )
    

    os.date

    os.date( [format|'%c'], [time] )
    Formats the given time (default now) with the specified format. Format is either '*t' for a table, or follows strftime.
    os.date( '%H:%M:%S %e %B %Y' )
    

    os.time

    os.time( [t] )
    Returns the unix timestamp for the specified table, or now.
    os.time()
    

    os.difftime

    os.difftime( t2, t1 )
    Returns the number of seconds from t1 and t2.

    String library[edit | edit source]

    In all string functions, the first character is at position 1, not position 0 as in C, PHP, and JavaScript. Indexes may be negative, in which case they count from the end of the string: position -1 is the last character in the string, -2 is the second-last, and so on.

    The string library assumes one-byte character encodings. It cannot handle Unicode characters. To operate on Unicode strings, use the corresponding methods in the Scribunto mw.ustring library. These won't be covered here.

    Function Description Example

    string.find

    string.find( s, pattern, [init|1], [plain|false] )
    Looks for the first match of pattern in the string s. If it finds a match, then find returns the offsets in s where this occurrence starts and ends; otherwise, it returns nil. If the pattern has captures, then in a successful match the captured values are also returned after the two indices.

    Init specifies where to start searching, can be negative.

    Plain turns off the pattern matching facilities, so the function does a plain "find substring" operation.

    local start, stop, str = string.find( 'Hello world', '(%w+)$' ) --> 7	11	'world'
    

    string.format

    string.format( formatstring, ... )
    Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string).

    The format string uses a limited subset of the printf format specifiers:

    • Recognized flags are '-', '+', ' ', '#', and '0'.
    • Integer field widths up to 99 are supported. '*' is not supported.
    • Integer precisions up to 99 are supported. '*' is not supported.
    • Length modifiers are not supported.
    • Recognized conversion specifiers are 'c', 'd', 'i', 'o', 'u', 'x', 'X', 'e', 'E', 'f', 'g', 'G', 's', '%', and the non-standard 'q'.
    • Positional specifiers (e.g. "%2$s") are not supported.

    The conversion specifier 'q' is like 's', but formats the string in a form suitable to be safely read back by the Lua interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written.

    local str = string.format( '%d is called %s', 5, 'five' )
    

    string.gmatch

    string.gmatch( s, pattern )
    Returns an iterator function that, each time it is called, returns the next captures from pattern over string s. If pattern specifies no captures, then the whole match is produced in each call.
    for s in string.gmatch( 'loop over words', '%w+' ) do
        mw.log( s )
    end
    

    string.gsub

    string.gsub( s, pattern, repl, [n|inf] )
    Returns a copy of s in which all (or the first n, if given) occurrences of the pattern have been replaced by a replacement string specified by repl, which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred.

    If repl is a string, then its value is used for replacement. The character % works as an escape character: any sequence in repl of the form %n, with n between 1 and 9, stands for the value of the n-th captured substring. The sequence %0 stands for the whole match, and the sequence %% stands for a single %.

    If repl is a table, then the table is queried for every match, using the first capture as the key; if the pattern specifies no captures, then the whole match is used as the key.

    If repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order; if the pattern specifies no captures, then the whole match is passed as a sole argument.

    If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).

    local str, n = string.gsub( 'hello world', 'hello', 'good' ) --> 'good world', 1
    

    string.len

    string.len( s )
    Identical to #s

    string.lower

    string.lower( s )
    Returns of a lowercase copy of the string.

    string.match

    string.match( s, pattern, [init|1] )
    Same as string.find() but doesn't return the start and stop indexes, only the captured pattern.
    local str = string.match( 'Hello world', '(%w+)$' ) --> 'world'
    

    string.rep

    string.rep( s, n )
    Returns n copies of str (as one string).

    string.reverse

    string.reverse( s )
    (bytewise) reverses the string.

    string.sub

    string.sub( s, i, [j|-1] )
    Returns the substring of s that starts at i and continues until j; i and j can be negative.
    local str = string.sub( 'hello world', -4 ) --> 'orld'
    

    string.upper

    string.upper( s )
    Returns of an uppercase copy of the string.

    Patterns[edit | edit source]

    Patterns are lua's equivalent of regular expressions. They're more limited, but they do the job well enough. See documentation for full information. Lua's base patterns operate on ASCII strings - use ustring functions and patterns for unicode strings.

    If you are familiar with Perl-compatible regular expressions (PCRE), the primary differences are:

    • % is the escape characters
    • . always matches all characters including newlines (single-line mode always on)
    • No case-insensitivity
    • No alternation (|)
    • Cannot use * + ? - on capture groups
    • No generalised finite quantifier ({m,n})
    • All quantifiers are greedy, except - (equivalent to *?)
    • No equivalent to \b or lookaheads/lookbehinds/non-capture groups

    Lua pattern character classes represent a group of characters:

    • . - all characters
    • %a - all letters
    • %c - all control characters
    • %d - all digits
    • %l - all lowercase letters
    • %p - all punctuation characters
    • %s - all whitespace characters
    • %u - all uppercase letters
    • %w - all alphanumeric characters
    • %x - all hexadecimal digits
    • %z - ASCII NUL character
    • All of the above, if the uppercase version is used (e.g. %A) means all characters not in that class.
    • [set] represents all characters in the set, e.g. [abc] matches a or b or c. Sets can contain character classes.
    • [^set] represents the characters not in the set.

    Table library[edit | edit source]

    Most functions in the table library assume that the table represents a sequence.

    Function Description Example

    table.concat

    table.concat( table, [sep|''], [i|1], [j|#table] )
    Given an array where all elements are strings or numbers, returns table[i] .. sep .. table[i+1] ··· sep .. table[j], but is much more efficient.
    local t = {'This', 'is', 'a', 'sentence.'}
    local str = table.concat( t, ' ' ) --> 'This is a sentence.'
    

    table.insert

    table.insert( table, value )

    table.insert( table, pos, value )

    Inserts element value at position pos in table, shifting up other elements to open space, if necessary. Default value of pos is #table + 1, i.e. append to the end.
    local t = {}
    table.insert( t, 5 )
    mw.log( t[1] ) --> 5
    

    table.remove

    table.remove( table, [pos|#table] )
    Removes and returns the element at position pos from table, shifting down other elements to close the space.
    local t = {1, 2}
    local last = table.remove( t ) --> 2
    

    table.sort

    table.sort( table, [comp|<] )
    Sorts the elements in table. comp is an optional sort function; if not specified the Lua operator < is used.
    local t = {3, 8, 9, 4, 1}
    table.sort( t ) --> {1, 3, 4, 8, 9}
    
    local function comp( i, j )
        return i > j
    end
    table.sort( t, comp ) --> {9, 8, 4, 3, 1}
    

    Scribunto library[edit | edit source]

    The Scribunto library are the functions provided by the extension, mostly related to wiki editing. We won't cover all of them, only the most notable.

    Base functions[edit | edit source]

    Function Description Example

    mw.clone

    mw.clone( value )
    Creates a deep copy of a value. All tables (and their metatables) are reconstructed from scratch. Functions are still shared, however.
    local t1 = {1}
    local t2 = t1
    local t3 = mw.clone( t1 )
    t1[1] = 2
    mw.log( t1[1] ) --> 2
    mw.log( t2[1] ) --> 2
    mw.log( t3[1] ) --> 1
    

    mw.getCurrentFrame

    mw.getCurrentFrame()
    Returns the current frame object, typically the frame object from the most recent #invoke.

    mw.loadData

    mw.loadData( module )
    See #Loading data.

    mw.dumpObject

    mw.dumpObject( object )
    Serializes object to a human-readable representation, then returns the resulting string. See #Table debugging.

    mw.log

    mw.log( ... )
    Prints strings to the console.
    mw.log( 5, 'hello', {} ) --> 5 'hello' 'table'
    

    Frame object[edit | edit source]

    Function Description Example

    frame.args

    frame.args
    Returns a table containing the frame arguments. See #Frames.

    frame:callParserFunction

    frame:callParserFunction( name, args )

    frame:callParserFunction( name, ... )
    frame:callParserFunction{ name = string, args = table }

    Call a parser function, returning an appropriate string. Whenever possible, native Lua functions or Scribunto library functions should be preferred to this interface.
    -- <nowiki>some text</nowiki>
    -- {{#tag:nowiki|some text}}
    frame:callParserFunction{ name = '#tag', args = { 'nowiki', 'some text' } }
    frame:callParserFunction( '#tag', { 'nowiki', 'some text' } )
    frame:callParserFunction( '#tag', 'nowiki', 'some text' )
    frame:callParserFunction( '#tag:nowiki', 'some text' )
    

    frame:expandTemplate

    frame:expandTemplate{ title = title, args = table }
    Returns the result of a template as a string. Slow compared to native Lua.
    -- {{template|arg1|arg2|name=arg3}}
    frame:expandTemplate{ title = 'template', args = { 'arg1', 'arg2', name = 'arg3' } }
    

    frame:extensionTag

    frame:extensionTag( name, content, args )

    frame:extensionTag{ name = string, content = string, args = table_or_string }

    This is equivalent to a call to frame:callParserFunction() with function name '#tag:' .. name and with content prepended to args.
    -- These are equivalent
    frame:extensionTag{ name = 'ref', content = 'some text', args = { name = 'foo', group = 'bar' } }
    frame:extensionTag( 'ref', 'some text', { name = 'foo', group = 'bar' } )
    

    frame:getParent

    frame:getParent()
    Returns the parent frame or nil if there is no parent frame. See #Frames

    frame:getTitle

    frame:getTitle()
    Returns the title associated with the frame as a string.
    local title = mw.getCurrentFrame():getParent():getTitle()
    

    frame:preprocess

    frame:preprocess( string )

    frame:preprocess{ text = string }

    This expands wikitext in the context of the frame, i.e. templates, parser functions, and parameters such as {{{1}}} are expanded. Used only as a last resort when nothing else works in Lua.
    local coins = mw.getCurrentFrame():preprocess( '{{Coins|10000}}' ) --> '<span class="coins inventory-image coins-10000 coins-pos">10,000</span>'
    

    HTML library[edit | edit source]

    The html library allows for easy construction of complex html structures. A mw.html object can be created using mw.html.create.

    Functions documented as mw.html.name are available on the global mw.html table; functions documented as html:name are methods of an mw.html object (see mw.html.create).

    Function Description Example

    mw.html.create

    mw.html.create( tagName, [args|nil] )
    Creates a new mw.html object containing a tagName html element. You can also pass an empty string or nil as tagName in order to create an empty mw.html object.

    args can be a table with the following keys:

    • args.selfClosing: Force the current tag to be self-closing, even if mw.html doesn't recognize it as self-closing
    • args.parent: Parent of the current mw.html instance (intended for internal usage)
    local html = mw.html.create( 'table' )
    mw.log( html ) --> '<table></table>'
    

    mw.html:node

    html:node( [builder|nil] )
    Appends a child mw.html (builder) node to the current mw.html instance. If a nil parameter is passed, this is a no-op. A (builder) node is a string representation of an html element or another mw.html object.
    local span = mw.html.create( 'span' )
    local html = mw.html.create( 'table' ):node( span )
    mw.log( html ) --> '<table><span></span></table>'
    

    mw.html:wikitext

    html:wikitext( ... )
    Appends an undetermined number of wikitext strings to the mw.html object.

    Note that this stops at the first nil item.

    local span = mw.html.create( 'span' ):wikitext( 'hello', 'World' )
    mw.log( span ) --> '<span>helloWorld</span>'
    

    mw.html:tag

    html:tag( tagName, [args|nil] )
    Appends a new child node with the given tagName to the builder, and returns a mw.html instance representing that new node. The args parameter is identical to that of mw.html.create.
    local html = mw.html.create( 'table' ):tag( 'span' ):done()
    mw.log( html ) --> '<table><span></span></table>'
    

    mw.html:attr

    html:attr( name, [value|nil] )

    html:attr( table )

    Set an HTML attribute with the given name and value on the node. Alternatively a table holding name->value pairs of attributes to set can be passed. In the first form, a value of nil causes any attribute with the given name to be unset if it was previously set.
    local html = mw.html.create( 'table' ):attr( 'id', 'hello' ):tag( 'span' ):attr{ value = '1000', name = 'price' }:done()
    mw.log( html ) --> '<table id="hello"><span value="1000" name="price"></span></table>'
    

    mw.html:addClass

    html:addClass( [class|nil] )
    Adds a class name to the node's class attribute. If a nil parameter is passed, this is a no-op.
    local span = mw.html.create( 'span' ):addClass( 'coins' )
    mw.log( span ) --> '<span class="coins"></span>'
    

    mw.html:css

    html:css( name, [value|nil] )

    html:css( table )

    Set a CSS property with the given name and value on the node. Alternatively a table holding name->value pairs of properties to set can be passed. In the first form, a value of nil causes any property with the given name to be unset if it was previously set.
    local span = mw.html.create( 'span' ):css( 'height', '100px' )
    mw.log( span ) --> '<span style="height:100px"></span>'
    
    local span = mw.html.create( 'span' ):css{ height = '100px', width = '200px' }
    mw.log( span ) --> '<span style="height:100px;width:200px"></span>'
    

    mw.html:done

    html:done()
    Returns the parent node under which the current node was created. This is a convenience function to allow the construction of several child nodes to be chained together into a single statement.
    local html = mw.html.create( 'table' ):tag( 'div' ):tag( 'span' ):done():done()
    mw.log( html ) --> '<table><div><span></span></div></table>'
    
    local html = mw.html.create( 'table' ):tag( 'div' ):done():tag( 'span' ):done()
    mw.log( html ) --> '<table><div></div><span></span></table>'
    

    mw.html:allDone

    html:allDone()
    Like html:done(), but traverses all the way to the root node of the tree and returns it.
    local html = mw.html.create( 'table' ):tag( 'div' ):tag( 'span' ):allDone()
    mw.log( html ) --> '<table><div><span></span></div></table>'
    

    More functions are available at #Module:Mw.html_extension.

    When to use done()[edit | edit source]

    When chaining mw.html functions it is important to understand what the done() functions does and when to use it.

    Remember how a function's output as function argument works, and that tables are stored by reference. Also a small spoiler about object oriented programming in Lua, objects are really just clever manipulated tables. So when we are talking about an mw.html object, we mean a table with some extra functionality specific for the html library. Another spoiler is what the : operator really does; it just passed the table we are querying as the first function argument.

    local html = mw.html.create( 'table' ) -- Create mw.html object
    
    -- This
    html:tag( 'span' )
    
    -- Is the same as
    html.tag( html, 'span' ) -- Query the html table for a function 'tag' and pass the html table as its first argument
    

    So with the above information we can write our chained mw.html functions a little different:

    local html = mw.html.create( 'table' ) -- Create mw.html object
    
    -- This
    local result = html:tag( 'span' ):done():tag( 'div' ):done()
    
    -- Is almost the same as
    local temp1 = html.tag( html, 'span' )
    local temp2 = temp1.done( temp1 )
    local temp3 = temp2.tag( temp2, 'div' )
    local result = temp3.done( temp3 )
    
    -- But written as
    local result = temp3.done( temp2.tag( temp1.done( html.tag( html, 'span' ) ), 'div' ) ) -- In reality the temp variables are never really created as the output of one function is directly used as the input of the other
    
    mw.log( html == temp2 ) --> true
    mw.log( html == result ) --> true
    mw.log( html == temp1.parent ) --> true
    mw.log( html.nodes[1] == temp1 ) --> true
    mw.log( html.nodes[2] == temp3 ) --> true
    

    As we can see above, tag() returns a child object of html, and done() returns the parent again. Also only the output of the last function is stored in result. This means if we would have skipped the last done() the result would store one of the child tables and when we later convert this to a string only this child would be converted.

    local html = mw.html.create( 'table' ):tag( 'span' )
    mw.log( html ) --> '<span></span>'
    
    local html = mw.html.create( 'table' ):tag( 'span' ):done()
    mw.log( html ) --> '<table><span></span></table>'
    
    local html = mw.html.create( 'table' )
    html:tag( 'span' ) -- Returned result of 'tag' is ignored, 'html' still points to the top most object
    mw.log( html ) --> '<table><span></span></table>'
    
    Conclusion[edit | edit source]
    • Use done() or allDone() when the output of the last function is stored in a variable:
    local html = mw.html.create( 'table' ):tag( 'span' ):allDone()
    
    • Use done() when you want to create a neighbour node instead of a child node:
    local html = mw.html.create( 'table' ):tag( 'span' ):done():tag( 'span' ):done()
    mw.log( html ) --> '<table><span></span><span></span></table>'
    
    • Don't use done() when you want to create a child node:
    local html = mw.html.create( 'table' ):tag( 'span' ):tag( 'div' ):allDone()
    mw.log( html ) --> '<table><span><div></div></span></table>'
    
    • No need to use done() or allDone() when its output isn't stored in a variable, using it has no effect but can be added for making your code pretty.
    local html = mw.html.create( 'table' )
    html:tag( 'span' ):tag( 'div' )
    mw.log( html ) --> '<table><span><div></div></span></table>'
    

    Splitting up in multiple blocks[edit | edit source]

    It's often needed to split the creation of our final html structure in sections with other code or conditional statements in between. This is done by storing child nodes in temporary variables:

    local html = mw.html.create( 'table' ) -- Master variable which always links to the root of our tree
    
    -- Some code ...
    
    local row = html:tag( 'tr' ):attr( 'row_number', 1 )
    
    if condition then
        row:tag( 'td' ):wikitext( 'Condition is true' )
    else
        row:tag( 'td' ):wikitext( 'Condition is false' )
    end
    
    row = html:tag( 'tr' ):attr( 'row_number', 2 )
    
    if not condition then
        row:tag( 'td' ):wikitext( 'Condition is true' )
    else
        row:tag( 'td' ):wikitext( 'Condition is false' )
    end
    
    mw.log( html ) --> '<table><tr row_number="1"><td>Condition is false</td></tr><tr row_number="2"><td>Condition is true</td></tr></table>'
    

    Style guide[edit | edit source]

    • Keep a master variable which always points to the root of the tree.
    • For short chains you can keep it on one line, but for longer chains (3 functions or longer) it is customary to slit it up over multiple lines.
    • When using the tag() function you increase the indentation and done() decreases it.
    local html = mw.html.create( 'table' )
    html:tag( 'tr')
            :addClass( 'table-bg-green' )
            :tag( 'td' )
                :attr( 'value', 1000 )
                :wikitext( '[[Rune dagger]]' )
            :done()
            :tag( 'td' )
                :attr( 'value', 2000 )
                :wikitext( '[[Rune sword]]' )
            :done()
        :done()
        :tag( 'tr' )
            :tag( 'td' )
                :attr( 'value', 1000 )
                :wikitext( '[[Rune dagger]]' )
            :done() -- Has no use other than making this block prettier
        :done() -- Same here
    
    -- ...
    
    local row = html:tag( 'tr' )
    row:tag( 'td' )
            :attr( 'value', 1000 )
            :wikitext( '[[Rune dagger]]' )
        :done() -- Also only for looks
    
    mw.log( html ) --[=[ <table>
                            <tr class="table-bg-green">
                                <td value="1000">[[Rune dagger]]</td>
                                <td value="2000">[[Rune sword]]</td>
                            </tr>
                            <tr>
                                <td value="1000">[[Rune dagger]]</td>
                            </tr>
                            <tr>
                                <td value="1000">[[Rune dagger]]</td>
                            </tr>
                        </table>
    ]=]
    

    Language library[edit | edit source]

    The language library allows us to format text to the standards of a specific language; on this wiki this will always be English.

    Functions documented as mw.language.name are available on the global mw.language table; functions documented as lang:name are methods of a language object (see mw.getContentLanguage).

    Function Description Example

    mw.language.getContentLanguage

    mw.language.getContentLanguage()

    mw.getContentLanguage()

    Returns a new language object for the wiki's default content language.
    local lang = mw.getContentLanguage()
    

    mw.language:lc

    lang:lc( s )
    Converts the string to lowercase.
    local str = mw.getContentLanguage():lc( 'HELLO WORLD' ) --> 'hello world'
    

    mw.language:lcfirst

    lang:lcfirst( s )
    Converts the first character of the string to lowercase.
    local str = mw.getContentLanguage():lcfirst( 'HELLO WORLD' ) --> 'hELLO WORLD'
    

    mw.language:uc

    lang:uc( s )
    Converts the string to uppercase.
    local str = mw.getContentLanguage():uc( 'hello world' ) --> 'HELLO WORLD'
    

    mw.language:ucfirst

    lang:ucfirst( s )
    Converts the first character of the string to uppercase.
    local str = mw.getContentLanguage():ucfirst( 'hello world' ) --> 'Hello world'
    

    mw.language:formatNum

    lang:formatNum( n, [options|nil] )
    Formats a number with grouping and decimal separators. The options is a table of options, which can be:
    • noCommafy: Set true to omit grouping separators and use a dot (.) as the decimal separator.
    local str = mw.getContentLanguage():formatNum( 123456.78 ) --> '123,456.78'
    

    Text library[edit | edit source]

    The text library provides some common text processing functions missing from the String library and the Ustring library. These functions are safe for use with UTF-8 strings.

    Function Description Example

    mw.text.decode

    mw.text.decode( s )
    Replaces the &lt;, &gt;, &amp;, &quot;, and &nbsp; HTML entities in the string with the corresponding characters.
    local str = mw.text.decode( '&lt;&gt;&amp;&quot;&nbsp;' ) --> '<>&" '
    

    mw.text.encode

    mw.text.encode( s, [charset|'<>&"\' '] )
    Replaces characters in a string with HTML entities. Characters <, >, &, ", and the non-breaking space are replaced with the appropriate named entities; all others are replaced with numeric entities.

    If charset is supplied, it should be a string as appropriate to go inside brackets in a Ustring pattern, i.e. the "set" in [set]. The default charset is '<>&"\' ' (the space at the end is the non-breaking space, U+00A0).

    local str = mw.text.encode( '<>&"' ) --> '&lt;&gt;&amp;&quot;'
    

    mw.text.jsonDecode

    mw.text.jsonDecode( s, [flags|0] )
    Decodes a JSON string. flags is 0 or a combination (use +) of the flags:
    • mw.text.JSON_PRESERVE_KEYS: prevents JSON's zero-based arrays renumbering to Lua one-based sequence tables.
    • mw.text.JSON_TRY_FIXING: relaxes certain requirements in JSON, such as no terminal comma in arrays or objects.
    local json = mw.text.jsonDecode( '{"a":"a","b":2,"1":1,"2":2,"3":3}' )
    mw.logObject( json ) --[=[
                                table#1 {
                                    1,
                                    2,
                                    3,
                                    ["a"] = "a",
                                    ["b"] = 2,
                                }
                            ]=]
    

    mw.text.jsonEncode

    mw.text.jsonEncode( value, [flags|0] )
    Encode a JSON string. Errors are raised if the passed value cannot be encoded in JSON. flags is 0 or a combination (use +) of the flags:
    • mw.text.JSON_PRESERVE_KEYS: prevents Lua's one-based sequence tables to JSON zero-based arrays renumbering.
    • mw.text.JSON_PRETTY: return the json in a human readable format instead of in a compacted single line string.
    local t = {
        a = 'a',
        b = 2,
        1,
        2,
        3
    }
    local json = mw.text.jsonEncode( t ) --> '{"a":"a","b":2,"1":1,"2":2,"3":3}'
    

    mw.text.listToText

    mw.text.listToText( list, [separator|','], [conjunction|'and'] )
    Same as table.concat() but with a different separator at the end.
    local str = mw.text.listToText( { 1, 2, 3, 4, 5 } ) --> '1, 2, 3, 4 and 5'
    

    mw.text.nowiki

    mw.text.nowiki( s )
    Replaces certain characters with HTML entities to prevent their interpretation as wikitext.
    local text = mw.text.nowiki( '* [[Rune dagger|dagger]] <span>hello world</span>' ) --> '&#42; &#91;&#91;Rune dagger&#124;dagger&#93;&#93; &#60;span&#62;hello world&#60;/span&#62;'
    

    mw.text.split

    mw.text.split( s, pattern, [plain|false] )
    Returns a table with the string split into substrings at boundaries matching the pattern. If plain is true, pattern will be interpreted as a literal string rather than as a Lua pattern.
    local split = mw.text.split( 'a b\tc\nd', '%s' ) --> { 'a', 'b', 'c', 'd' }
    

    mw.text.gsplit

    mw.text.gsplit( s, pattern, [plain|false] )
    Returns an iterator to loop over the returned substrings from mw.text.split.
    for s in mw.text.gsplit( 'a b\tc\nd', '%s' ) do
        mw.log( s )
    end
    --[
    a
    b
    c
    d
    ]
    

    mw.text.trim

    mw.text.trim( s, [charset|'\t\r\n\f '] )
    Remove whitespace or other characters from the beginning and end of a string.
    local text = mw.text.trim( '  hello \n' ) --> 'hello'
    

    Title library[edit | edit source]

    Function Description Example

    mw.title.getCurrentTitle

    mw.title.getCurrentTitle()
    Returns the title object for the current page.

    The title object contains some useful properties:

    • namespace: The namespace number.
    • text: The title of the page, without the namespace or interwiki prefixes.
    • prefixedText: The title of the page, with the namespace and interwiki prefixes.
    • fullText: The title of the page, with the namespace and interwiki prefixes and the fragment. Interwiki is not returned if equal to the current.
    • rootText: If this is a subpage, the title of the root page without prefixes. Otherwise, the same as title.text.
    • baseText: If this is a subpage, the title of the page it is a subpage of without prefixes. Otherwise, the same as title.text.
    • subpageText: If this is a subpage, just the subpage name. Otherwise, the same as title.text.
    • partialUrl(): Returns title.text encoded as it would be in a URL.
    • fullUrl( query, proto ): Returns the full URL (with optional query table/string) for this title. proto may be specified to control the scheme of the resulting url: "http", "https", "relative" (the default), or "canonical".
    • localUrl( query ): Returns the local URL (with optional query table/string) for this title.
    • canonicalUrl( query ): Returns the canonical URL (with optional query table/string) for this title.
    • getContent(): Returns the (unparsed) content of the page, or nil if there is no page. The page will be recorded as a transclusion.

    For a full list see Title objects

    local title = mw.title.getCurrentTitle().text
    

    URI library[edit | edit source]

    Function Description Example

    mw.uri.encode

    mw.uri.encode( s, [enctype|'QUERY'] )
    Percent-encodes the string. enctype can have the following values:
    • 'QUERY', encodes spaces using '+' for use in query strings.
    • 'PATH' encodes spaces as %20.
    • 'WIKI' encodes spaces as '_'.
    local uri = mw.uri.encode( 'hello world' ) --> 'hello+world'
    

    mw.uri.decode

    mw.uri.decode( s, [enctype|'QUERY'] )
    Percent-decodes the string.
    local uri = mw.uri.decode( 'hello+world' ) --> 'hello world'
    

    mw.uri.fullUrl

    mw.uri.fullUrl( page, [query|nil] )
    Returns a URI object for the local URL for a page, with optional query string/table.
    local uri = mw.uri.fullUrl( 'Rune dagger', 'action=purge' ) --> '//runescape.wiki/w/Rune_dagger?action=purge'
    

    libraryUtil[edit | edit source]

    This library contains methods useful for generating descriptive errors when arguments of a function don't match expected types; used primarily when implementing libraries. It is not loaded by default so you will have to require it to use.

    local libraryUtil = require( 'libraryUtil' )
    
    Function Description Example

    libraryUtil.checkType

    libraryUtil.checkType( name, argIdx, arg, expectType, [nilOk|false] )
    Raises an error if type( arg ) does not match expectType. In addition, no error will be raised if arg is nil and nilOk is true.

    name is the name of the calling function, and argIdx is the position of the argument in the argument list. These are used in formatting the error message.

    local libraryUtil = require( 'libraryUtil' )
    
    local function hello( str, num )
        libraryUtil.checkType( 'hello', 1, str, 'string' )
        libraryUtil.checkType( 'hello', 2, num, 'number' )
    end
    
    hello( 5, 5 ) --> Lua error in console input at line 14: bad argument #1 to 'hello' (string expected, got number).
    hello( 'a', {} ) --> Lua error in console input at line 15: bad argument #2 to 'hello' (number expected, got table).
    

    libraryUtil.checkTypeMulti

    libraryUtil.checkTypeMulti( name, argIdx, arg, expectTypes )
    Raises an error if type( arg ) does not match any of the strings in the array expectTypes.

    This is for arguments that have more than one valid type.

    local libraryUtil = require( 'libraryUtil' )
    
    local function hello( arg )
        libraryUtil.checkTypeMulti( 'hello', 1, arg, {'string', 'number'} )
    end
    
    hello( {}, 5 ) --> Lua error in console input at line 13: bad argument #1 to 'hello' (string or number expected, got table).
    

    libraryUtil.checkTypeForNamedArg

    libraryUtil.checkTypeForNamedArg( name, argName, arg, expectType, nilOk )
    Raises an error if type( arg ) does not match expectType. In addition, no error will be raised if arg is nil and nilOk is true.

    This is intended to be used as an equivalent to libraryUtil.checkType() in methods called using Lua's "named argument" syntax, func{ name = value }.

    local libraryUtil = require( 'libraryUtil' )
    
    local function hello( t )
        libraryUtil.checkTypeForNamedArg( 'hello', 'str', t.str, 'string' )
        libraryUtil.checkTypeForNamedArg( 'hello', 'num', t.num, 'number' )
    end
    
    hello{ str = 5, num = 5 } --> Lua error in console input at line 14: bad named argument str to 'hello' (string expected, got number).
    hello{ str = 'a', num = {} } --> Lua error in console input at line 15: bad named argument num to 'hello' (number expected, got table).
    

    libraryUtil.makeCheckSelfFunction

    libraryUtil.makeCheckSelfFunction( libraryName, varName, selfObj, selfObjDesc )
    This is intended for use in implementing "methods" on object tables that are intended to be called with the obj:method() syntax. It returns a function that should be called at the top of these methods with the self argument and the method name, which will raise an error if that self object is not selfObj. Objects will be explained more in depth at object oriented programming.
    local libraryUtil = require( 'libraryUtil' )
    
    local myLibrary = {}
    local checkSelf = libraryUtil.makeCheckSelfFunction( 'myLibrary', 'obj', myLibrary, 'myLibrary object' )
    myLibrary.__index = myLibrary
    
    function myLibrary.new()
        local obj = {}
    
        setmetatable( obj, myLibrary )
    
        return obj
    end
    
    function myLibrary:method( num )
        checkSelf( getmetatable( self ), 'method' )
        libraryUtil.checkType( 'method', 1, num, 'number' )
        mw.log( num )
    end
    
    ------------------
    
    local a = myLibrary.new()
    
    a:method( 5 ) --> 5
    a.method( 5 ) --> Lua error in console input at line 32: <myLibrary>: invalid <myLibrary object>. Did you call method with a dot instead of a colon, i.e. obj.method() instead of obj:method()?.
    a:method( 'str' ) --> Lua error in console input at line 33: bad argument #1 to 'method' (number expected, got string).
    

    Footnotes[edit | edit source]