RuneScape:Lua/Helper modules
This is a table of modules and functions that were created specifically for facilitating the creation of other modules. Documentation for modules here is done in the source code with Template:Helper module.
Module | Function | Type | Use |
---|---|---|---|
Addcommas | _add(arg) | Number | Formats the number arg with commas |
_strip(arg) | Number | Removes all commas from arg | |
Chart data | _main( args ) | table/chart | Turns a table/chart object into a json string. |
convertToXYFormat( ys, [xs|{}] ) | table, table | 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( func, start_x, end_x, [step|1] ) | function, number, number, number | 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( low_chance, high_chance, start_level, end_level ) | number, number, number, number | ||
newChart( [options] ) | table | 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( ... ) | table/dataSet object | Appends all given data sets to the chart.data.datasets table. | |
chart:addDataLabels( labels ) | table | Appends all items in labels to the chart.data.labels table. | |
chart:setDimensions( width, [height|width], [minWidth|400], [minHeight|400], [resizable|false] ) | number/string, number/string, number/string, number/string, boolean | 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, 40vw /40vh to dynamically scale the simensions to the viewport size (i.e. 40vw = 40% of browser's window width). If resizable is true, the chart can be dragged by the lower right corner to change its size. | |
chart:setTitle( [text|nil], [position|'top'] ) | string, string | Sets the label title of the chart. A value of nil will remove the current title. | |
chart:setXLabel( [label|nil] ) | string | Sets the label for the x axis. Only works on chart types 'line', 'bar', 'horizontalBar', 'bubble' and 'scatter'. If used without arguments it will remove the current label. | |
chart:setYLabel( [label|nil] ) | string | Sets the label for the y axis. Only works on chart types 'line', 'bar', 'horizontalBar', 'bubble' and 'scatter'. If used without arguments it will remove the current label. | |
chart:setXLimits( [min|nil], [max|nil], [step|nil] ) | number, number, number | 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 'horizontalBar', 'bubble' and 'scatter'. | |
chart:setYLimits( [min|nil], [max|nil], [step|nil] ) | number, number, number | 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( [min|nil], [max|nil], [step|nil] ) | number, number, number | 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( [type|nil] ) | string | 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 'bubble', 'scatter' and 'horizontalBar'. | |
chart:setYAxisType( [type|nil] ) | string | Same as chart:setXAxisType() but for the y axis. Only works on chart types 'line', 'bubble', 'scatter' and 'bar'. | |
chart:setOptions( options ) | table | 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{ options = {scales = {ticks = {max = 100}}} } while {options = {scales = {ticks = {min = 0}}}} already exists will result in {options = {scales = {ticks = {min = 0, max = 100}}}} . | |
chart:makeMwLoadDataCompatible() | N/A | Strips metatables so that it can be loaded by mw.loadData() making it possible to display the table using {{Chart data|<module name>}} . This should only be used at the very end when you are done creating your chart. | |
chart:newDataSet( [options] ) | table | Returns a new dataSet object which is also automatically added to the chart datasets table. | |
dataSet:addData( data ) | table | 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( data ) | number/table | Append a single value to the dataSet.data array. Same as table.insert( dataSet.data, data ) . | |
dataSet:setOptions( options ) | table | Sets options using Chart.js format. | |
Clean image | clean(args) | string | Input args is a table with fields:
|
Combat level | _calc(attack, strength, defence, ranged, magic, hitpoints, prayer) | Number, String, Table | Returns three values:
|
Currency | _amount(num, type) | string | Takes the number and formats it with the currency type (coins, nocoins). |
DPLlua | ask( ... ) | tables | 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 contains include , the result will be a simple list of page names.
{ <pagename#1>, <pagename#2>, <pagename#3>, } A query with an { ['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 If the config value The output contains a If the DPL throws an error it will be available in the Differences with normal DPL:
|notcategory = val#1 |notcategory = val#2Note of warning, if you include content containing § symbols the result may be unreliable. 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 § characters and the { and } characters are replaced by ❴ (U+2774) and ❵ (U+2775). Use include = '{some template}, {some template}:1:2:3' instead for the problem parameters. |
Edit button | (text) | string | Creates an edit button for the current page that the module is invoked ontext defaults to "edit" |
Enum | any(enum, [fn], [clone|false]) | table, function/nil, boolean/nil | 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. |
all(enum, [fn], [clone|false]) | table, function/nil, boolean/nil | 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. | |
each(enum, fn, [clone|false]) | table, function, boolean/nil | Loops over the array part of enum and passes each element as the first argument to fn . This function returns nothing. | |
sum(enum, [clone|false]) | table, boolean/nil | Returns the sum of all array elements in enum . | |
reduce(enum, fn, [accumulator|enum[1]], [clone|false]) | table, function, any, boolean/nil | 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. | |
scan(enum, fn, [accumulator|enum[1]], [clone|false]) | table, function, any, boolean/nil | Same as reduce() but each step is appended to a table. This table is then returned. | |
find(enum, fn, [default|nil], [clone|false]) | table, function, any, boolean/nil | 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(enum, fn, [default|nil], [clone|false]) | table, function, any, boolean/nil | 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. | |
max_by(enum, fn, [clone|false]) | table, function, boolean/nil | 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. | |
map(enum, fn, [clone|false]) | table, function, boolean/nil | 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. | |
filter(enum, [fn], [clone|false]) | table, function/nil, boolean/nil | 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. | |
reject(enum, [fn], [clone|false]) | table, function, boolean/nil | The opposite of filter() . | |
split(enum, count, [clone|false]) | table, number, boolean/nil | Returns two tables where the first is equivalent to slice(enum, 1, count) and the second slice(enum, count+1, #enum) . | |
slice(enum, [start|1], [stop|#enum], [clone|false]) | table, number/nil, number/nil, boolean/nil | Returns a table containing all the elements of enum between the start and stop indices. The start and stop indices are inclusive. | |
take(enum, count, [clone|false]) | table, number, boolean/nil | Returns only the first table of split(enum, count) . | |
take_every(enum, n, [clone|false]) | table, number, boolean/nil | Returns a table containing every nth element of enum . | |
unique(enum, [fn], [clone|false]) | table, function/nil, boolean/nil | 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(enums, [clone|false]) | table, boolean/nil | 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}} | |
intersect(enum1, enum2, [clone|false]) | table, table, boolean/nil | Returns true if both sets have at least one element with equal values. | |
contains(enum, elem, [clone|false]) | table, any, boolean/nil | Returns true if enum contains elem , otherwise returns false. | |
take_from(enum, index, count) | table, number, number | Returns count number of elements, starting at index | |
Exchange | _price(arg) | String | Gets the current GE price of item named arg |
_price(arg, multi, format, round, default) | String | Gets the current GE price of item named arg, multiplied by [multi] (default 1), rounded to [round] decimal places (default unrounded), and if [format] is true, formatted with thousands separators (default false). If the item does not exist, an error is thrown, unless [default] is set, in which case it will return the given [default] value. | |
_value(arg) | String | Gets the value of item named arg | |
_highalch(arg) | String | Gets the high alch value of item named arg, accounting for alch multipliers | |
_lowalch(arg) | String | Gets the low alch value of item named arg, accounting for alch multipliers | |
_alchable(arg) | String | Gets the alchablility (boolean) of item named arg | |
_alchmultiplier(arg) | String | Gets the alchemy multiplier of item named arg (default 0.6) | |
_limit(arg) | String | Gets the GE limit of item named arg | |
_diff(arg, format) | String | Gets the difference of the current GE price and the previous GE price for item named arg. If format is true, formats the number with thousands separators | |
_exists(arg) | String | Checks if the module for item named arg exists, returns a boolean | |
FetchItemStats | defaultVersion(pagename) | String, String | Returns a string of the default version (format: Pagename#Versionname ) that can be used for further SMW searches. Also returns a wikilink to the matched page name (following redirects from the given pagename , as the second return value. |
gemwprice(gemwname) | Number | Returns the GE value for the given item, or -1 if the item does not exist. | |
value(item_smwname) | Number | Returns the item value for either the specified SMW version (if the given name links to a specific item), or the version that is shown on the page by default (the same version as returned by defaultVersion . | |
equipmentStats( | { Table1, Table2, ... } | Fetches all item stats for a list of given SMW names. If an ambiguous item name is given anywhere in this list (i.e. one that has different versions), this function will not automatically pick the one that would otherwise be chosen by defaultVersion . A specific SMW name needs to be entered for this function.
Sort keys and sort orders may be provided as optional second and third arguments. No custom sorting will be applied if these arrays are empty or Possible sorting orders are: 'ascending', 'asc', 'descending', 'desc', 'reverse', 'random' and 'rand'. The returned stats are formatted as a Table containing a single Table for each of the items, in the order given by the sort keys, or the default SMW sorting. The stats that are returned in each of these Tables are: { astab = 'Stab attack bonus', aslash = 'Slash attack bonus', acrush = 'Crush attack bonus', amagic = 'Magic attack bonus', arange = 'Range attack bonus', dstab = 'Stab defence bonus', dslash = 'Slash defence bonus', dcrush = 'Crush defence bonus', dmagic = 'Magic defence bonus', drange = 'Range defence bonus', str = 'Strength bonus', mdmg = 'Magic Damage bonus', rstr = 'Ranged Strength bonus', prayer = 'Prayer bonus', weight = 'Weight', image = 'Image', subobj = 'Has subobject' } | |
Mainonly | _main(arg) | Any value | If the module is invoked in the content namespace, it will return arg, otherwise, it will return an empty string |
on_main() | N/A | Returns true if invoked in the content namespace, otherwise false | |
MergeArgs | merge | Frame | Merges the parent and frame args returning a table containing the arg values instead of an empty table with an attached metatable. Parent args overwrite invoke args allowing invoke args to be used as a "default" value for an argument. |
Mw.html extension | addClassIf(cond, class) | boolean, string | 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(cond, name, value) | boolean, string/table, string/nil | Similar to addClassIf | |
cssIf(cond, name, value) | boolean, string/table, string/nil | Similar to addClassIf | |
doneIf(cond) | boolean | Similar to addClassIf | |
tagIf(cond, tag) | boolean, string | Similar to addClassIf | |
wikitextIf(cond, text) | boolean, string | Similar to addClassIf | |
na() | N/A | Shortcut for :tag('td'):attr('data-sort-value', 0):attr('class','table-na'):wikitext('<small>N/A</small>'):done() | |
naIf(cond) | boolean | Similar to addClassIf | |
tr([settings]) | table/nil | 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:
| |
th([settings]) | string/table/nil | 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:
| |
td([settings]) | string/table/nil | 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(cond) | boolean | 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(cond) | boolean | Used together with IF() . | |
ELSE() | N/A | Used together with IF() . | |
END() | N/A | Used together with IF() . Make sure the IF-END tags are balanced, it wont throw an error if they are not. | |
exec(func, ...) | function, any | Call a function without breaking the chain. See module docs for more info. | |
addFunction(func, name) | function, string | Add a function to the mw.html class that can then be used on mw.html object. See module docs for more info. | |
Number | _round(num, dp) | float, int | Rounds num to a precision given by dp , if dp is not specified, it defaults to zero. Rounds half up. |
_short(str) | String | Convert numbers ending in k, m or b to the actual correct number. Example: 3.5k -> 3500 | |
PageListTools | pageswithcats(cats, [logging]) | table, boolean/nil | Returns a list of pages with the specified categories. Uses SMW. Each entry can consist of several categories AND-ed together with ' '. |
pageswithconditions(conditions, [logging]) | string, boolean/nil | Returns a list of pages that satisfies the given SMW conditions. | |
pagelistchecks(pages, [logging]) | table, boolean/nil | Given a list of pages, this function returns lists of pages that are either non-existing (invalid), redirects or duplicates. | |
pageswithcatsdpl(cats, [logging]) | table, boolean/nil | Returns a list of pages with the specified categories. Uses DPL. Each entry can consist of several categories AND-ed together with '&'. | |
pageswithconditionsdpl(conditions, [logging]) | table, boolean/nil | Returns a list of pages that satisfies the given DPL conditions. | |
Paramtest | is_empty(arg) | String | Returns true if arg is not defined or contains only whitespace |
has_content(arg) | String | Returns true if arg exists and does not only contain whitespace | |
default_to(arg1,arg2) | String, Any value | If arg1 exists and does not only contain whitespace, the function returns arg1, otherwise returns arg2 | |
defaults{ {arg1,arg2},...} | {String, Any value}... | Does the same as default_to() run over every table passed; for technical reasons, all nil are replaced with false | |
Reftag | {attr} | table | Table of attributes may include:
|
Rgba | new( red, [green|0], [blue|0], [alpha|1] );;
new( hex ) | number/string, number/nil, number/nil, number/nil | 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. |
rgba:lighten( val ) | number | 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( val ) | number | 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( num ) | number | Returns a new rgba object with its hue num degrees rotated. Decimal values are allowed. | |
rgba:saturate( val ) | number | 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( val ) | number | Returns a new rgba object with its alpha value set to val . val is clipped to the range 0-1. | |
rgba:clone() | N/A | Returns a copy with the same values. | |
Tables | _row(row, elts, header) | mw.html object, table/string, boolean | 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, data) | mw.html object, table | Adds tr rows and td /th cells to the html object, the data for the rows and cells is specified by data . | |
Top icons | _main(args) | String | Returns a string that adds top icons to the page. args must be a table of arguments. Numbered arguments must have values of rs , rsc , meta or wp . To provide a specific pagename on the top icon link, specify named arguments with those same indices, with the value being the external pagename. |
Yesno | (arg) | Any value | Reads arg for yes/no and returns the appropriate boolean or nil |
(arg1,arg2) | Any value, Any value | Reads arg1 for yes/no and returns the appropriate boolean; returns arg2 if arg1 was not an applicable value |