Near-Reality:Lua/Helper modules

Revision as of 11:04, 4 October 2022 by Jacmob (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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.

ModuleFunctionTypeUse
Addcommas_add(arg)NumberFormats the number arg with commas
_strip(arg)NumberRemoves all commas from arg
Coins_amount(coins)NumberReturns a formatted string with a coins icon and the amount of coins. See Template:Coins for examples.
DPLluaask( ... )tablesask 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 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 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.

The output contains a time field so you don't need to use %DPLTIME%.

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
  • Surrogate templates (e.g. include = '{template|other template}' 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
  • 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 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)stringCreates an edit button for the current page that the module is invoked on

text defaults to "edit"
Enumany(enum, [fn], [clone|false])table, function/nil, boolean/nilLoops 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/nilLoops 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/nilLoops 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/nilReturns the sum of all array elements in enum.
reduce(enum, fn, [accumulator|enum[1]], [clone|false])table, function, any, boolean/nilLoops 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/nilSame 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/nilLoops 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/nilLoops 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/nilLoops 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/nilLoops 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/nilLoops 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/nilThe opposite of filter().
split(enum, count, [clone|false])table, number, boolean/nilReturns 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/nilReturns 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/nilReturns only the first table of split(enum, count).
take_every(enum, n, [clone|false])table, number, boolean/nilReturns a table containing every nth element of enum.
unique(enum, [fn], [clone|false])table, function/nil, boolean/nilReturns 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/nilGroups 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/nilReturns true if both sets have at least one element with equal values.
contains(enum, elem, [clone|false])table, any, boolean/nilReturns true if enum contains elem, otherwise returns false.
take_from(enum, index, count)table, number, numberReturns count number of elements, starting at index
Exchange_price(arg)StringGets the current GE price of item named arg
_price(arg, multi, format, round, default)StringGets 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)StringGets the value of item named arg
_highalch(arg)StringGets the high alch value of item named arg, accounting for alch multipliers
_lowalch(arg)StringGets the low alch value of item named arg, accounting for alch multipliers
_alchable(arg)StringGets the alchablility (boolean) of item named arg
_alchmultiplier(arg)StringGets the alchemy multiplier of item named arg (default 0.6)
_limit(arg)StringGets the GE limit of item named arg
_diff(arg, format)StringGets 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)StringChecks if the module for item named arg exists, returns a boolean
Mainonly_main(arg)Any valueIf the module is invoked in the content namespace, it will return arg, otherwise, it will return an empty string
on_main()N/AReturns true if invoked in the content namespace, otherwise false
Mw.html extensionaddClassIf(cond, class)boolean, stringIf 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/nilSimilar to addClassIf
cssIf(cond, name, value)boolean, string/table, string/nilSimilar to addClassIf
doneIf(cond)booleanSimilar to addClassIf
tagIf(cond, tag)boolean, stringSimilar to addClassIf
wikitextIf(cond, text)boolean, stringSimilar to addClassIf
na()N/AShortcut for :tag('td'):attr('data-sort-value', 0):attr('class','table-na'):wikitext('<small>N/A</small>'):done()
naIf(cond)booleanSimilar to addClassIf
tr([settings])table/nilShortcut 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([settings])string/table/nilShortcut 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([settings])string/table/nilSame 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)booleanAllows 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)booleanUsed together with IF().
ELSE()N/AUsed together with IF().
END()N/AUsed together with IF(). Make sure the IF-END tags are balanced, it wont throw an error if they are not.
exec(func, ...)function, anyCall a function without breaking the chain. See module docs for more info.
addFunction(func, name)function, stringAdd 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, intRounds num to a precision given by dp, if dp is not specified, it defaults to zero. Rounds half up.
_short(str)StringConvert numbers ending in k, m or b to the actual correct number. Example: 3.5k -> 3500
Paramtestis_empty(arg)StringReturns true if arg is not defined or contains only whitespace
has_content(arg)StringReturns true if arg exists and does not only contain whitespace
default_to(arg1,arg2)String, Any valueIf 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
Top icons_main(args)StringReturns 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 valueReads arg for yes/no and returns the appropriate boolean or nil
(arg1,arg2)Any value, Any valueReads arg1 for yes/no and returns the appropriate boolean; returns arg2 if arg1 was not an applicable value