|
|
| (3 intermediate revisions by 2 users not shown) |
| Line 1: |
Line 1: |
| --[[
| | local export = {} |
| ------------------------------------------------------------------------------------
| |
| -- table (formerly TableTools) --
| |
| -- --
| |
| -- This module includes a number of functions for dealing with Lua tables. --
| |
| -- It is a meta-module, meant to be called from other Lua modules, and should --
| |
| -- not be called directly from #invoke. --
| |
| ------------------------------------------------------------------------------------
| |
| --]]
| |
|
| |
|
| --[[ | | --[==[ intro: |
| Inserting new values into a table using a local "index" variable, which is
| | This module provides functions for dealing with Lua tables. All of them, except for two helper functions, take a table |
| incremented each time, is faster than using "table.insert(t, x)" or
| | as their first argument. |
| "t[#t + 1] = x". See the talk page.
| |
| ]]
| |
|
| |
|
| local export = {} | | Some functions are available as methods in the arrays created by [[Module:array]]. |
| | |
| | Functions by what they do: |
| | * Create a new table: |
| | ** `shallowCopy`, `deepCopy`, `removeDuplicates`, `numKeys`, `compressSparseArray`, `keysToList`, `reverse`, `invert`, `listToSet` |
| | * Create an array: |
| | ** `removeDuplicates`, `numKeys`, `compressSparseArray`, `keysToList`, `reverse` |
| | * Return information about the table: |
| | ** `size`, `length`, `contains`, `isArray`, `deepEquals` |
| | * Treat the table as an array (that is, operate on the values in the array portion of the table: values indexed by |
| | consecutive integers starting at {1}): |
| | ** `removeDuplicates`, `length`, `contains`, `serialCommaJoin`, `reverseIpairs`, `reverse`, `invert`, `listToSet`, `isArray` |
| | * Treat a table as a sparse array (that is, operate on values indexed by non-consecutive integers): |
| | ** `numKeys`, `maxIndex`, `compressSparseArray`, `sparseConcat`, `sparseIpairs` |
| | * Generate an iterator: |
| | ** `sparseIpairs`, `sortedPairs`, `reverseIpairs` |
| | * Other functions: |
| | ** `sparseConcat`, `serialCommaJoin`, `reverseConcat` |
| | |
| | The original version was a copy of {{w|Module:TableTools}} on Wikipedia via [[c:Module:TableTools|Module:TableTools]] on |
| | Commons, but in the course of time this module has been almost completely rewritten, with many new functions added. The |
| | main legacy of this is the use of camelCase for function names rather than snake_case, as is normal in the English |
| | Wiktionary. |
| | ]==] |
| | |
| | local load_module = "Module:load" |
| | local math_module = "Module:math" |
|
| |
|
| local libraryUtil = require("libraryUtil")
| |
| local table = table | | local table = table |
|
| |
|
| local checkType = libraryUtil.checkType
| |
| local checkTypeMulti = libraryUtil.checkTypeMulti
| |
| local concat = table.concat | | local concat = table.concat |
| local format = string.format | | local dump = mw.dumpObject |
| local getmetatable = getmetatable
| |
| local insert = table.insert
| |
| local ipairs = ipairs | | local ipairs = ipairs |
| local is_callable = require("Module:fun").is_callable | | local ipairs_default_iter = ipairs{export} |
| local is_positive_integer -- defined as export.isPositiveInteger below
| |
| local keys_to_list -- defined as export.keysToList below
| |
| local next = next | | local next = next |
| local pairs = pairs | | local pairs = pairs |
| local rawequal = rawequal | | local require = require |
| local rawget = rawget
| | local select = select |
| local setmetatable = setmetatable | | local signed_index -- defined as export.signedIndex |
| local sort = table.sort | | local table_len -- defined as export.length |
| local string_sort = require("Module:collation").string_sort | |
| local type = type | | local type = type |
|
| |
|
| local infinity = math.huge
| | --[==[ |
| | | Loaders for functions in other modules, which overwrite themselves with the target function when called. This ensures modules are only loaded when needed, retains the speed/convenience of locally-declared pre-loaded functions, and has no overhead after the first call, since the target functions are called directly in any subsequent calls.]==] |
| local function _check(funcName, expectType)
| | local function is_integer(...) |
| if type(expectType) == "string" then
| | is_integer = require(math_module).is_integer |
| return function(argIndex, arg, nilOk)
| | return is_integer(...) |
| checkType(funcName, argIndex, arg, expectType, nilOk)
| |
| end
| |
| else
| |
| return function(argIndex, arg, expectType, nilOk)
| |
| if type(expectType) == "table" then
| |
| if not nilOk or arg ~= nil then
| |
| -- checkTypeMulti() doesn't accept a fifth `nilOk` argument, unlike the other check functions.
| |
| checkTypeMulti(funcName, argIndex, arg, expectType)
| |
| end
| |
| else
| |
| checkType(funcName, argIndex, arg, expectType, nilOk)
| |
| end
| |
| end
| |
| end | |
| end | | end |
|
| |
|
| --[==[
| | local function safe_require(...) |
| Return true if the given value is a positive integer, and false if not. Although it doesn't operate on tables, it is
| | safe_require = require(load_module).safe_require |
| included here as it is useful for determining whether a given table key is in the array part or the hash part of a
| | return safe_require(...) |
| table.
| |
| ]==]
| |
| function export.isPositiveInteger(v)
| |
| return type(v) == "number" and v >= 1 and v % 1 == 0 and v < infinity | |
| end | | end |
| is_positive_integer = export.isPositiveInteger
| |
|
| |
|
| --[==[ | | --[==[ |
| Return a clone of an object. If the object is a table, the value returned is a new table, but all subtables and functions are shared. Metamethods are respected, but the returned table will have no metatable of its own.
| | Given an array and a signed index, returns the true table index. If the signed index is negative, the array will be counted from the end, where {-1} is the highest index in the array; otherwise, the returned index will be the same. To aid optimization, the first argument may be a number representing the array length instead of the array itself; this is useful when the array length is already known, as it avoids recalculating it each time this function is called.]==] |
| ]==] | | function export.signedIndex(t, k) |
| function export.shallowcopy(orig) | | if not is_integer(k) then |
| if type(orig) ~= "table" then | | error("index must be an integer") |
| return orig | |
| end
| |
| local copy = {}
| |
| for k, v in pairs(orig) do
| |
| copy[k] = v
| |
| end | | end |
| return copy | | return k < 0 and (type(t) == "table" and table_len(t) or t) + k + 1 or k |
| end | | end |
| | signed_index = export.signedIndex |
|
| |
|
| do
| | --[==[ |
| local function rawpairs(t)
| | An iterator which works like `pairs`, but ignores any `__pairs` metamethod.]==] |
| return next, t
| | function export.rawPairs(t) |
| end
| | return next, t, nil |
| | |
| local function make_copy(orig, memo, mt_flag, keep_loaded_data)
| |
| if type(orig) ~= "table" then
| |
| return orig
| |
| end
| |
| local memoized = memo[orig]
| |
| if memoized ~= nil then
| |
| return memoized
| |
| end
| |
| local mt = getmetatable(orig)
| |
| local loaded_data = mt and mt.mw_loadData
| |
| if loaded_data and keep_loaded_data then
| |
| memo[orig] = orig
| |
| return orig
| |
| end
| |
| local copy = {}
| |
| memo[orig] = copy
| |
| for k, v in (loaded_data and pairs or rawpairs)(orig) do
| |
| copy[make_copy(k, memo, mt_flag, keep_loaded_data)] = make_copy(v, memo, mt_flag, keep_loaded_data)
| |
| end
| |
| if loaded_data then
| |
| return copy
| |
| elseif mt_flag == "keep" then
| |
| setmetatable(copy, mt)
| |
| elseif mt_flag ~= "none" then
| |
| setmetatable(copy, make_copy(mt, memo, mt_flag, keep_loaded_data))
| |
| end
| |
| return copy
| |
| end
| |
| | |
| --[==[
| |
| Recursive deep copy function. Preserves copied identities of subtables.
| |
| A more powerful version of {mw.clone}, with customizable options.
| |
| * By default, metatables are copied, except for data loaded via mw.loadData (see below). If `metatableFlag` is set to "none", the copy will not have any metatables at all. Conversely, if `metatableFlag` is set to "keep", then the cloned table (and all its members) will have the exact same metatable as their original version.
| |
| * If `keepLoadedData` is true, then any data loaded via {mw.loadData} will not be copied, and the original will be used instead. This is useful in iterative contexts where it is necessary to copy data being destructively modified, because objects loaded via mw.loadData are immutable.
| |
| * Notes:
| |
| *# Protected metatables will not be copied (i.e. those hidden behind a __metatable metamethod), as they are not
| |
| accessible by Lua's design. Instead, the output of the __metatable method will be used instead.
| |
| *# When iterating over the table, the __pairs metamethod is ignored, since this can prevent the table from being properly cloned.
| |
| *# Data loaded via mw.loadData is a special case in two ways: the metatable is stripped, because otherwise the cloned table throws errors when accessed; in addition, the __pairs metamethod is used, since otherwise the cloned table would be empty.]==]
| |
| function export.deepcopy(orig, metatableFlag, keepLoadedData)
| |
| return make_copy(orig, {}, metatableFlag, keepLoadedData)
| |
| end
| |
| end | | end |
|
| |
|
| --[==[ | | --[==[ |
| Append any number of tables together and returns the result. Compare the Lisp expression {(append list1 list2 ...)}.
| | An iterator which works like `ipairs`, but ignores any `__ipairs` metamethod.]==] |
| ]==] | | function export.rawIpairs(t) |
| function export.append(...) | | return ipairs_default_iter, t, 0 |
| local ret, n = {}, 0 | |
| for i = 1, arg.n do
| |
| for _, v in ipairs(arg[i]) do
| |
| n = n + 1
| |
| ret[n] = v
| |
| end
| |
| end
| |
| return ret
| |
| end | | end |
|
| |
|
| --[==[ | | --[==[ |
| Extend an existing list by a new list, modifying the existing list in-place. Compare the Python expression
| | This returns the length of a table, or the first integer key n counting from 1 such that t[n + 1] is nil. It is a more reliable form of the operator `#`, which can become unpredictable under certain circumstances due to the implementation of tables under the hood in Lua, and therefore should not be used when dealing with arbitrary tables. `#` also does not use metamethods, so will return the wrong value in cases where it is desirable to take these into account (e.g. data loaded via `mw.loadData`). If `raw` is set, then metamethods will be ignored, giving the true table length. |
| {list.extend(new_items)}.
| |
|
| |
|
| `options` is an optional table of additional options to control the behavior of the operation. The following options are
| | For arrays, this function is faster than `export.size`.]==] |
| recognized:
| | function export.length(t, raw) |
| * `insertIfNot`: Use {export.insertIfNot()} instead of {table.insert()}, which ensures that duplicate items do not get
| | local n = 0 |
| inserted (at the cost of an O((M+N)*N) operation, where M = #list and N = #new_items).
| | if raw then |
| * `key`: As in {insertIfNot()}. Ignored otherwise.
| | for i in ipairs_default_iter, t, 0 do |
| * `pos`: As in {insertIfNot()}. Ignored otherwise.
| | n = i |
| ]==] | |
| function export.extendList(list, new_items, options) | |
| local check = _check("extendList", "table") | |
| check(1, list) | |
| check(2, new_items)
| |
| check(3, options, true)
| |
| for _, item in ipairs(new_items) do
| |
| if options and options.insertIfNot then
| |
| export.insertIfNot(list, item, options)
| |
| else
| |
| insert(list, item) | |
| end | | end |
| | return n |
| end | | end |
| | repeat |
| | n = n + 1 |
| | until t[n] == nil |
| | return n - 1 |
| end | | end |
| | table_len = export.length |
|
| |
|
| --[==[
| | local function getIteratorValues(i, j , step, t_len) |
| Remove duplicate values from an array. Non-positive-integer keys are ignored. The earliest value is kept, and all subsequent duplicate values are removed, but otherwise the array order is unchanged.
| | i, j = i and signed_index(t_len, i), j and signed_index(t_len, j) |
| -- -0, NaN and -NaN have special handling, as they can't be used as table keys.
| | if step == nil then |
| ]==]
| | i, j = i or 1, j or t_len |
| function export.removeDuplicates(t) | | return i, j, j < i and -1 or 1 |
| checkType("removeDuplicates", 1, t, "table")
| | elseif step == 0 or not is_integer(step) then |
| local ret, n, seen, _neg_0, _pos_nan, _neg_nan = {}, 0, {} | | error("step must be a non-zero integer") |
| for _, v in ipairs(t) do
| | elseif step < 0 then |
| local v_key = v
| | return i or t_len, j or 1, step |
| -- -0
| |
| if v == 0 and 1 / v < 0 then
| |
| _neg_0 = _neg_0 or {}
| |
| v_key = _neg_0
| |
| -- NaN and -NaN. | |
| elseif v ~= v then
| |
| if format("%f", v) == "nan" then
| |
| _pos_nan = _pos_nan or {}
| |
| v_key = _pos_nan
| |
| else
| |
| _neg_nan = _neg_nan or {}
| |
| v_key = _neg_nan
| |
| end
| |
| end
| |
| if not seen[v_key] then
| |
| n = n + 1
| |
| ret[n] = v
| |
| seen[v_key] = true
| |
| end
| |
| end | | end |
| return ret | | return i or 1, j or t_len, step |
| end | | end |
|
| |
|
| --[==[ | | --[==[ |
| Given a table, return an array containing the numbers of any numerical keys that have non-nil values, sorted in | | Given an array `list` and function `func`, iterate through the array applying {func(r, k, v)}, and returning the result, |
| numerical order.
| | where `r` is the value calculated so far, `k` is an index, and `v` is the value at index `k`. For example, |
| ]==]
| | {reduce(array, function(a, _, v) return a + v end)} will return the sum of `array`. |
| function export.numKeys(t, checked)
| |
| if not checked then
| |
| checkType("numKeys", 1, t, "table")
| |
| end
| |
| local nums = {}
| |
| local index = 1
| |
| for k in pairs(t) do
| |
| if is_positive_integer(k) then
| |
| nums[index] = k
| |
| index = index + 1
| |
| end
| |
| end
| |
| sort(nums)
| |
| return nums
| |
| end
| |
|
| |
|
| --[==[
| | Optional arguments: |
| Return the maximum index of a table or array that possibly has holes in it, or 0 if there are no numerical keys in the
| | * `i`: start index; negative values count from the end of the array |
| table.
| | * `j`: end index; negative values count from the end of the array |
| ]==]
| | * `step`: step increment |
| function export.maxIndex(t)
| | These must be non-zero integers. The function will determine where to iterate from, whether to iterate forwards or |
| local max = 0
| | backwards and by how much, based on these inputs (see examples below for default behaviours). |
| for k in pairs(t) do
| |
| if is_positive_integer(k) and k > max then
| |
| max = k
| |
| end
| |
| end
| |
| return max
| |
| end
| |
|
| |
|
| --[==[
| | Examples: |
| This takes an array with one or more nil values, and removes the nil values
| | # No values for i, j or step results in forward iteration from the start to the end in steps of 1 (the default). |
| while preserving the order, so that the array can be safely traversed with
| | # step=-1 results in backward iteration from the end to the start in steps of 1. |
| ipairs.
| | # i=7, j=3 results in backward iteration from indices 7 to 3 in steps of 1 (i.e. step=-1). |
| ]==] | | # j=-3 results in forward iteration from the start to the 3rd last index. |
| function export.compressSparseArray(t) | | # j=-3, step=-1 results in backward iteration from the end to the 3rd last index.]==] |
| checkType("compressSparseArray", 1, t, "table") | | function export.reduce(t, func, i, j, step) |
| local ret = {} | | i, j, step = getIteratorValues(i, j, step, table_len(t)) |
| local index = 1
| | local ret = t[i] |
| local nums = export.numKeys(t)
| | for k = i + step, j, step do |
| for _, num in ipairs(nums) do | | ret = func(ret, k, t[k]) |
| ret[index] = t[num] | |
| index = index + 1
| |
| end | | end |
| return ret | | return ret |
| end | | end |
|
| |
| --[==[
| |
| This is an iterator for sparse arrays. It can be used like ipairs, but can handle nil values.
| |
| ]==]
| |
| function export.sparseIpairs(t)
| |
| checkType("sparseIpairs", 1, t, "table")
| |
| local nums = export.numKeys(t)
| |
| local i = 0
| |
| return function()
| |
| i = i + 1
| |
| local key = nums[i]
| |
| if key then
| |
| return key, t[key]
| |
| else
| |
| return nil, nil
| |
| end
| |
| end
| |
| end
| |
|
| |
| --[==[
| |
| This returns the size of a key/value pair table. It will also work on arrays, but for arrays it is more efficient to
| |
| use the # operator.
| |
| ]==]
| |
| function export.size(t)
| |
| checkType("size", 1, t, "table")
| |
| local i = 0
| |
| for _ in pairs(t) do
| |
| i = i + 1
| |
| end
| |
| return i
| |
| end
| |
|
| |
| --[==[
| |
| This returns the length of a table, or the first integer key n counting from 1 such that t[n + 1] is nil. It is similar to the operator #, but may return a different value when metamethods are involved. Intended to be used on data loaded with mw.loadData. For other tables, use #.
| |
| ]==]
| |
| function export.length(t)
| |
| local i = 0
| |
| repeat
| |
| i = i + 1
| |
| until t[i] == nil
| |
| return i - 1
| |
| end
| |
|
| |
|
| |
|
| do | | do |
| local function is_equivalent(a, b, memo, include_mt) | | local function replace(t, func, i, j, step, generate) |
| -- Raw equality check.
| | local t_len = table_len(t) |
| if rawequal(a, b) then
| | -- Normalized i, j and step, based on the inputs. |
| return true
| | local norm_i, norm_j, norm_step = getIteratorValues(i, j, step, t_len) |
| -- If not equal, a and b can only be equivalent if they're both tables. | | if norm_step > 0 then |
| elseif not (type(a) == "table" and type(b) == "table") then
| | i, j, step = 1, t_len, 1 |
| return false
| |
| end
| |
| -- If a and b have been compared before, they must be equivalent. | |
| local memo_a = memo[a] | |
| if not memo_a then | |
| memo[a] = {[b] = true} | |
| elseif memo_a[b] then
| |
| return true
| |
| else | | else |
| memo_a[b] = true | | i, j, step = t_len, 1, -1 |
| end | | end |
| local memo_b = memo[b] | | -- "Signed" variables are multiplied by -1 if `step` is negative. |
| if not memo_b then | | local t_new, signed_i, signed_j = generate and {} or t, norm_i * step, norm_j * step |
| memo[b] = {[a] = true}
| | for k = i, j, step do |
| else -- We know memo_b won't have a, since memo_a didn't have b. | | -- Replace the values iff they're within the i to j range and `step` wouldn't skip the key. |
| memo_b[a] = true
| | -- Note: i > j if `step` is positive; i < j if `step` is negative. Otherwise, the range is empty. |
| end
| | local signed_k = k * step |
| -- If include_mt is set, check the metatables are equivalent.
| | if signed_k >= signed_i and signed_k <= signed_j and (k - norm_i) % norm_step == 0 then |
| if (
| | t_new[k] = func(k, t[k]) |
| include_mt and | | -- Otherwise, add the existing value if `generate` is set. |
| not is_equivalent(getmetatable(a), getmetatable(b), memo, true)
| | elseif generate then |
| ) then
| | t_new[k] = t[k] |
| return false
| |
| end
| |
| -- Fast check: loop over keys in a, checking if an equivalent value exists at the same key in b. Any tables-as-keys are set aside for the laborious check instead.
| |
| local tablekeys_a, tablekeys_b, kb
| |
| for ka, va in next, a do
| |
| if type(ka) == "table" then | |
| if not tablekeys_a then | |
| tablekeys_a = {[ka] = va}
| |
| else
| |
| tablekeys_a[ka] = va
| |
| end
| |
| else | |
| local vb = rawget(b, ka)
| |
| -- Faster to avoid recursion if possible, as we know va is not nil.
| |
| if vb == nil or not is_equivalent(va, vb, memo, include_mt) then
| |
| return false
| |
| end
| |
| end
| |
| -- Iterate over b simultaneously (to check it's the same size and to grab any tables-as-keys for the laborious check), but also separately (since it might iterate in a different order, as this is unpredictable in Lua).
| |
| local vb
| |
| kb, vb = next(b, kb)
| |
| -- Fail if b runs out of key/value pairs too early.
| |
| if kb == nil then
| |
| return false
| |
| elseif type(kb) == "table" then | |
| if not tablekeys_b then | |
| tablekeys_b = {[kb] = vb}
| |
| else
| |
| tablekeys_b[kb] = vb
| |
| end
| |
| end | | end |
| end | | end |
| -- Fail if there are too many key/value pairs in b. | | return t_new |
| if next(b, kb) ~= nil then
| |
| return false
| |
| -- If tablekeys_a == tablekeys_b they must be both nil, meaning there are no tables-as-keys to check, so success.
| |
| elseif tablekeys_a == tablekeys_b then
| |
| return true
| |
| -- If only one them exists, then the tables can't be equivalent.
| |
| elseif not (tablekeys_a and tablekeys_b) then
| |
| return false
| |
| end
| |
| -- Laborious check: for each table-as-key in tablekeys_a, loop over tablekeys_b looking for an equivalent key/value pair.
| |
| for ka, va in next, tablekeys_a do
| |
| local kb
| |
| while true do
| |
| local vb
| |
| kb, vb = next(tablekeys_b, kb)
| |
| -- Fail if no equivalent is found.
| |
| if kb == nil then
| |
| return false
| |
| elseif (
| |
| is_equivalent(ka, kb, memo, include_mt) and
| |
| is_equivalent(va, vb, memo, include_mt)
| |
| ) then
| |
| -- Remove match to prevent double-matching (and for speed).
| |
| tablekeys_b[kb] = nil
| |
| break
| |
| end
| |
| end
| |
| end
| |
| -- Success if tablekeys_b is now empty.
| |
| return next(tablekeys_b) == nil
| |
| end | | end |
|
| |
|
| --[==[ | | --[==[ |
| Recursively compare two values that may be tables, and returns true if all key-value pairs are structurally equivalent. Note that this handles arbitrary nesting of subtables (including recursive nesting) to any depth, for keys as well as values. | | Given an array `list` and function `func`, iterate through the array applying {func(k, v)} (where `k` is an index, and |
| | | `v` is the value at index `k`), replacing the relevant values with the result. For example, |
| If `include_mt` is true, then metatables are also compared.]==]
| | {apply(array, function(_, v) return 2 * v end)} will double each member of the array. |
| function export.deepEquals(a, b, include_mt)
| |
| return is_equivalent(a, b, {}, include_mt)
| |
| end
| |
| end
| |
| | |
| do
| |
| local function get_nested(a, b, ...)
| |
| if a == nil then
| |
| return nil
| |
| elseif ... ~= nil then
| |
| return get_nested(a[b], ...)
| |
| end
| |
| return a[b]
| |
| end
| |
| | |
| --[==[
| |
| Given a table and an arbitrary number of keys, will successively access subtables using each key in turn, returning the value at the final key. For example, if {t} is { {[1] = {[2] = {[3] = "foo"}}}}, {export.getNested(t, 1, 2, 3)} will return {"foo"}.
| |
| | |
| If no subtable exists for a given key value, returns nil, but will throw an error if a non-table is found at an intermediary key.
| |
| ]==]
| |
| function export.getNested(a, ...)
| |
| if a == nil or ... == nil then
| |
| error("Must provide a table and at least one key.")
| |
| end
| |
| return get_nested(a, ...)
| |
| end | |
| end
| |
| | |
| do
| |
| local function set_nested(a, b, c, ...)
| |
| if ... == nil then
| |
| a[c] = b
| |
| return
| |
| end
| |
| local t = a[c]
| |
| if t == nil then
| |
| t = {}
| |
| a[c] = t
| |
| end
| |
| return set_nested(t, b, ...)
| |
| end
| |
| | |
| --[==[
| |
| Given a table, value and an arbitrary number of keys, will successively access subtables using each key in turn, and sets the value at the final key. For example, if {t} is { {} }, {export.setNested(t, "foo", 1, 2, 3)} will modify {t} to { {[1] = {[2] = {[3] = "foo"} } } }.
| |
| | |
| If no subtable exists for a given key value, one will be created, but the function will throw an error if a non-table value is found at an intermediary key.
| |
| | |
| Note: the parameter order (table, value, keys) differs from functions like rawset, because the number of keys can be arbitrary. This is to avoid situations where an additional argument must be appended to arbitrary lists of variables, which can be awkward and error-prone: for example, when handling variable arguments ({{lua|...}}) or function return values.
| |
| ]==] | |
| function export.setNested(a, b, ...)
| |
| if a == nil or b == nil or ... == nil then
| |
| error("Must provide a table, value and at least one key.")
| |
| end
| |
| return set_nested(a, b, ...)
| |
| end
| |
| end
| |
| | |
| --[==[
| |
| Given a list and a value to be found, return true if the value is in the array
| |
| portion of the list. Comparison is by value, using `deepEquals`.
| |
| ]==]
| |
| function export.contains(list, x, options) | |
| local check = _check("contains", "table")
| |
| check(1, list)
| |
| check(3, options, true)
| |
| | |
| if options and options.key then
| |
| x = options.key(x)
| |
| end
| |
| for _, v in ipairs(list) do
| |
| if options and options.key then
| |
| v = options.key(v)
| |
| end
| |
| if export.deepEquals(v, x) then return true end
| |
| end
| |
| return false
| |
| end
| |
| | |
| --[==[
| |
| Given a general table and a value to be found, return true if the value is in
| |
| either the array or hashmap portion of the table. Comparison is by value, using
| |
| `deepEquals`.
| |
| | |
| NOTE: This used to do shallow comparison by default and accepted a third
| |
| "deepCompare" param to do deep comparison. This param is still accepted but now
| |
| ignored.
| |
| ]==]
| |
| function export.tableContains(tbl, x)
| |
| checkType("tableContains", 1, tbl, "table")
| |
| for _, v in pairs(tbl) do
| |
| if export.deepEquals(v, x) then return true end
| |
| end
| |
| return false
| |
| end
| |
| | |
| --[==[
| |
| Given a `list` and a `new_item` to be inserted, append the value to the end of the list if not already present
| |
| (or insert at an arbitrary position, if `options.pos` is given; see below). Comparison is by value, using {deepEquals}.
| |
|
| |
|
| `options` is an optional table of additional options to control the behavior of the operation. The following options are | | Optional arguments: |
| recognized:
| | * `i`: start index; negative values count from the end of the array |
| * `pos`: Position at which insertion happens (i.e. before the existing item at position `pos`). | | * `j`: end index; negative values count from the end of the array |
| * `key`: Function of one argument to return a comparison key, as with {deepEquals}. The key function is applied to both | | * `step`: step increment |
| `item` and the existing item in `list` to compare against, and the comparison is done against the results.
| | These must be non-zero integers. The function will determine where to iterate from, whether to iterate forwards or |
| This is useful when inserting a complex structure into an existing list while avoiding duplicates.
| | backwards and by how much, based on these inputs (see examples below for default behaviours). |
| * `combine`: Function of three arguments (the existing item, the new item and the position, respectively) to combine an
| |
| existing item with `new_item`, when `new_item` is found in `list`. If unspecified, the existing item is
| |
| left alone.
| |
|
| |
|
| Return {false} if entry already found, {true} if inserted.
| | Examples: |
| | | # No values for i, j or step results in forward iteration from the start to the end in steps of 1 (the default). |
| For compatibility, `pos` can be specified directly as the third argument in place of `options`, but this is not
| | # step=-1 results in backward iteration from the end to the start in steps of 1. |
| recommended for new code.
| | # i=7, j=3 results in backward iteration from indices 7 to 3 in steps of 1 (i.e. step=-1). |
| | | # j=-3 results in forward iteration from the start to the 3rd last index. |
| NOTE: This function is O(N) in the size of the existing list. If you use this function in a loop to insert several
| | # j=-3, step=-1 results in backward iteration from the end to the 3rd last index.]==] |
| items, you will get O(M*(M+N)) behavior, effectively O((M+N)^2). Thus it is not recommended to use this unless you are
| | function export.apply(t, func, i, j, step) |
| sure the total number of items will be small. (An alternative for large lists is to insert all the items without
| | return replace(t, func, i, j, step, false) |
| checking for duplicates, and use {removeDuplicates()} at the end.)
| |
| ]==]
| |
| function export.insertIfNot(list, new_item, options)
| |
| local check = _check("insertIfNot") | |
| check(1, list, "table")
| |
| check(3, options, {"table", "number"}, true)
| |
| | |
| if type(options) == "number" then
| |
| options = {pos = options}
| |
| end
| |
| if options and options.combine then
| |
| local new_item_key
| |
| -- Don't use options.key and options.key(new_item) or new_item in case the key is legitimately false or nil.
| |
| if options.key then
| |
| new_item_key = options.key(new_item)
| |
| else
| |
| new_item_key = new_item
| |
| end
| |
| for i, item in ipairs(list) do
| |
| local item_key
| |
| if options.key then
| |
| item_key = options.key(item)
| |
| else
| |
| item_key = item
| |
| end
| |
| if export.deepEquals(item_key, new_item_key) then
| |
| local retval = options.combine(item, new_item, i)
| |
| if retval ~= nil then
| |
| list[i] = retval
| |
| end
| |
| return false
| |
| end
| |
| end
| |
| elseif export.contains(list, new_item, options) then
| |
| return false
| |
| end
| |
| if options and options.pos then
| |
| insert(list, options.pos, new_item)
| |
| else | |
| insert(list, new_item)
| |
| end
| |
| end
| |
| | |
| --[==[ | |
| Finds key for specified value in a given table. Roughly equivalent to reversing the key-value pairs in the table:
| |
| * {reversed_table = { [value1] = key1, [value2] = key2, ... }}
| |
| and then returning {reversed_table[valueToFind]}.
| |
| | |
| The value can only be a string or a number (not nil, a boolean, a table, or a function).
| |
| | |
| Only reliable if there is just one key with the specified value. Otherwise, the function returns the first key found,
| |
| and the output is unpredictable.
| |
| ]==] | |
| function export.keyFor(t, valueToFind) | |
| local check = _check("keyFor")
| |
| check(1, t, "table")
| |
| check(2, valueToFind, {"string", "number"})
| |
| | |
| for key, value in pairs(t) do
| |
| if value == valueToFind then | |
| return key
| |
| end
| |
| end
| |
| | |
| return nil
| |
| end
| |
| | |
| do
| |
| -- The default sorting function used in export.keysToList if no keySort is defined.
| |
| local function defaultKeySort(key1, key2)
| |
| -- "number" < "string", so numbers will be sorted before strings.
| |
| local type1, type2 = type(key1), type(key2)
| |
| if type1 ~= type2 then
| |
| return type1 < type2
| |
| end
| |
| -- string_sort fixes a bug in < whereby all codepoints above U+FFFF are treated as equal.
| |
| return string_sort(key1, key2)
| |
| end | | end |
|
| |
|
| --[==[ | | --[==[ |
| Return a list of the keys in a table, sorted using either the default table.sort function or a custom keySort function. | | Given an array `list` and function `func`, iterate through the array applying {func(k, v)} (where `k` is an index, and |
| If there are only numerical keys, numKeys is probably more efficient.
| | `v` is the value at index `k`), and return a shallow copy of the original array with the relevant values replaced. For example, |
| ]==]
| | {generate(array, function(_, v) return 2 * v end)} will return a new array in which each value has been doubled. |
| function export.keysToList(t, keySort, checked)
| |
| if not checked then
| |
| local check = _check("keysToList")
| |
| check(1, t, "table")
| |
| check(2, keySort, "function", true)
| |
| end
| |
| | |
| local list, i = {}, 0
| |
| for key in pairs(t) do
| |
| i = i + 1
| |
| list[i] = key
| |
| end
| |
| | |
| -- Use specified sort function, or otherwise defaultKeySort.
| |
| sort(list, keySort or defaultKeySort)
| |
| | |
| return list
| |
| end
| |
| keys_to_list = export.keysToList
| |
| end
| |
| | |
| --[==[
| |
| Iterates through a table, with the keys sorted using the keysToList function. If there are only numerical keys,
| |
| sparseIpairs is probably more efficient.
| |
| ]==]
| |
| function export.sortedPairs(t, keySort)
| |
| local check = _check("keysToList")
| |
| check(1, t, "table")
| |
| check(2, keySort, "function", true)
| |
| | |
| local list, i = keys_to_list(t, keySort, true), 0
| |
| | |
| return function()
| |
| i = i + 1
| |
| local key = list[i]
| |
| if key ~= nil then
| |
| return key, t[key]
| |
| end
| |
| end
| |
| end
| |
| | |
| do
| |
| local function iter(t, i)
| |
| i = i - 1
| |
| if i > 0 then
| |
| return i, t[i]
| |
| end
| |
| end
| |
| | |
| function export.reverseIpairs(t)
| |
| checkType("reverseIpairs", 1, t, "table")
| |
| -- Not safe to use #t, as it can be unpredictable if there is a hash part.
| |
| local i = 0
| |
| repeat
| |
| i = i + 1
| |
| until t[i] == nil
| |
| return iter, t, i
| |
| end
| |
| end
| |
| | |
| local function getIteratorValues(i, j , s, list)
| |
| i = (i and i < 0 and #list - i + 1) or i or (s and s < 0 and #list) or 1
| |
| j = (j and j < 0 and #list - j + 1) or j or (s and s < 0 and 1) or #list
| |
| s = s or (j < i and -1) or 1
| |
| if (
| |
| i == 0 or i % 1 ~= 0 or
| |
| j == 0 or j % 1 ~= 0 or
| |
| s == 0 or s % 1 ~= 0
| |
| ) then
| |
| error("Arguments i, j and s must be non-zero integers.")
| |
| end
| |
| return i, j, s
| |
| end
| |
| | |
| --[==[
| |
| Given an array `list` and function `func`, iterate through the array applying {func(r, k, v)}, and returning the result, | |
| where `r` is the value calculated so far, `k` is an index, and `v` is the value at index `k`. For example, | |
| {reduce(array, function(a, b) return a + b end)} will return the sum of `array`. | |
| | |
| Optional arguments:
| |
| * `i`: start index; negative values count from the end of the array
| |
| * `j`: end index; negative values count from the end of the array
| |
| * `s`: step increment
| |
| These must be non-zero integers. The function will determine where to iterate from, whether to iterate forwards or
| |
| backwards and by how much, based on these inputs (see examples below for default behaviours).
| |
| | |
| Examples:
| |
| # No values for i, j or s results in forward iteration from the start to the end in steps of 1 (the default).
| |
| # s=-1 results in backward iteration from the end to the start in steps of 1.
| |
| # i=7, j=3 results in backward iteration from indices 7 to 3 in steps of 1 (i.e. s=-1).
| |
| # j=-3 results in forward iteration from the start to the 3rd last index.
| |
| # j=-3, s=-1 results in backward iteration from the end to the 3rd last index.
| |
| Note: directionality generally only matters for `reduce`, but values of s > 1 (or s < -1) still affect the return value
| |
| of `apply`.
| |
| ]==]
| |
| | |
| function export.reduce(list, func, i, j, s)
| |
| i, j, s = getIteratorValues(i, j , s, list)
| |
| local ret = list[i]
| |
| for k = i + s, j, s do
| |
| ret = func(ret, k, list[k])
| |
| end
| |
| return ret
| |
| end
| |
|
| |
|
| --[==[
| | Optional arguments: |
| Given an array `list` and function `func`, iterate through the array applying {func(k, v)} (where `k` is an index, and
| | * `i`: start index; negative values count from the end of the array |
| `v` is the value at index `k`), and return an array of the resulting values. For example,
| | * `j`: end index; negative values count from the end of the array |
| {apply(array, function(a) return 2*a end)} will return an array where each member of `array` has been doubled.
| | * `step`: step increment |
| | | These must be non-zero integers. The function will determine where to iterate from, whether to iterate forwards or |
| Optional arguments: | | backwards and by how much, based on these inputs (see examples below for default behaviours). |
| * `i`: start index; negative values count from the end of the array | |
| * `j`: end index; negative values count from the end of the array | |
| * `s`: step increment | |
| These must be non-zero integers. The function will determine where to iterate from, whether to iterate forwards or | |
| backwards and by how much, based on these inputs (see examples below for default behaviours). | |
|
| |
|
| Examples: | | Examples: |
| # No values for i, j or s results in forward iteration from the start to the end in steps of 1 (the default). | | # No values for i, j or step results in forward iteration from the start to the end in steps of 1 (the default). |
| # s=-1 results in backward iteration from the end to the start in steps of 1. | | # step=-1 results in backward iteration from the end to the start in steps of 1. |
| # i=7, j=3 results in backward iteration from indices 7 to 3 in steps of 1 (i.e. s=-1). | | # i=7, j=3 results in backward iteration from indices 7 to 3 in steps of 1 (i.e. step=-1). |
| # j=-3 results in forward iteration from the start to the 3rd last index. | | # j=-3 results in forward iteration from the start to the 3rd last index. |
| # j=-3, s=-1 results in backward iteration from the end to the 3rd last index. | | # j=-3, step=-1 results in backward iteration from the end to the 3rd last index.]==] |
| Note: directionality makes the most difference for `reduce`, but values of s > 1 (or s < -1) still affect the return
| | function export.generate(t, func, i, j, step) |
| value of `apply`.
| | return replace(t, func, i, j, step, true) |
| ]==] | |
| function export.apply(list, func, i, j, s) | |
| local modified_list = export.deepcopy(list)
| |
| i, j, s = getIteratorValues(i, j , s, modified_list)
| |
| for k = i, j, s do
| |
| modified_list[k] = func(k, modified_list[k])
| |
| end | | end |
| return modified_list
| |
| end | | end |
|
| |
|
| Line 738: |
Line 218: |
| * `i`: start index; negative values count from the end of the array | | * `i`: start index; negative values count from the end of the array |
| * `j`: end index; negative values count from the end of the array | | * `j`: end index; negative values count from the end of the array |
| * `s`: step increment | | * `step`: step increment |
| These must be non-zero integers. The function will determine where to iterate from, whether to iterate forwards or | | These must be non-zero integers. The function will determine where to iterate from, whether to iterate forwards or |
| backwards and by how much, based on these inputs (see examples below for default behaviours). | | backwards and by how much, based on these inputs (see examples below for default behaviours). |
|
| |
|
| Examples: | | Examples: |
| # No values for i, j or s results in forward iteration from the start to the end in steps of 1 (the default). | | # No values for i, j or step results in forward iteration from the start to the end in steps of 1 (the default). |
| # s=-1 results in backward iteration from the end to the start in steps of 1. | | # step=-1 results in backward iteration from the end to the start in steps of 1. |
| # i=7, j=3 results in backward iteration from indices 7 to 3 in steps of 1 (i.e. s=-1). | | # i=7, j=3 results in backward iteration from indices 7 to 3 in steps of 1 (i.e. step=-1). |
| # j=-3 results in forward iteration from the start to the 3rd last index. | | # j=-3 results in forward iteration from the start to the 3rd last index. |
| # j=-3, s=-1 results in backward iteration from the end to the 3rd last index. | | # j=-3, step=-1 results in backward iteration from the end to the 3rd last index.]==] |
| ]==] | | function export.all(t, func, i, j, step) |
| function export.all(list, func, i, j, s) | | i, j, step = getIteratorValues(i, j, step, table_len(t)) |
| i, j, s = getIteratorValues(i, j , s, list) | | for k = i, j, step do |
| local ret = true
| | if not func(k, t[k]) then |
| for k = i, j, s do | | return false |
| ret = ret and not not (func(k, list[k])) | | end |
| if not ret then break end | |
| end | | end |
| return ret | | return true |
| end | | end |
|
| |
|
| Line 766: |
Line 245: |
| * `i`: start index; negative values count from the end of the array | | * `i`: start index; negative values count from the end of the array |
| * `j`: end index; negative values count from the end of the array | | * `j`: end index; negative values count from the end of the array |
| * `s`: step increment | | * `step`: step increment |
| These must be non-zero integers. The function will determine where to iterate from, whether to iterate forwards or | | These must be non-zero integers. The function will determine where to iterate from, whether to iterate forwards or |
| backwards and by how much, based on these inputs (see examples below for default behaviours). | | backwards and by how much, based on these inputs (see examples below for default behaviours). |
|
| |
|
| Examples: | | Examples: |
| # No values for i, j or s results in forward iteration from the start to the end in steps of 1 (the default). | | # No values for i, j or step results in forward iteration from the start to the end in steps of 1 (the default). |
| # s=-1 results in backward iteration from the end to the start in steps of 1. | | # step=-1 results in backward iteration from the end to the start in steps of 1. |
| # i=7, j=3 results in backward iteration from indices 7 to 3 in steps of 1 (i.e. s=-1). | | # i=7, j=3 results in backward iteration from indices 7 to 3 in steps of 1 (i.e. step=-1). |
| # j=-3 results in forward iteration from the start to the 3rd last index. | | # j=-3 results in forward iteration from the start to the 3rd last index. |
| # j=-3, s=-1 results in backward iteration from the end to the 3rd last index. | | # j=-3, step=-1 results in backward iteration from the end to the 3rd last index.]==] |
| ]==] | | function export.any(t, func, i, j, step) |
| function export.any(list, func, i, j, s) | | i, j, step = getIteratorValues(i, j, step, table_len(t)) |
| i, j, s = getIteratorValues(i, j , s, list) | | for k = i, j, step do |
| local ret = false
| | if not not (func(k, t[k])) then |
| for k = i, j, s do | | return true |
| ret = ret or not not (func(k, list[k])) | | end |
| if ret then break end | |
| end | | end |
| return ret | | return false |
| end | | end |
|
| |
|
| Line 793: |
Line 271: |
| Options: | | Options: |
| * `conj`: Conjunction to use; defaults to {"and"}. | | * `conj`: Conjunction to use; defaults to {"and"}. |
| * `italicizeConj`: Italicize conjunction: for [[Module:also]] | | * `punc`: Punctuation to use; default to {","}. |
| * `dontTag`: Don't tag the serial comma and serial {"and"}. For error messages, in which HTML cannot be used. | | * `dontTag`: Don't tag the serial comma and serial {"and"}. For error messages, in which HTML cannot be used. |
| ]==] | | * `dump`: Each item will be serialized with {mw.dumpObject}. For warnings and error messages.]==] |
| function export.serialCommaJoin(seq, options) | | function export.serialCommaJoin(seq, options) |
| local check = _check("serialCommaJoin", "table") | | -- If the `dump` option is set, determine the table length as part of the |
| check(1, seq) | | -- dump loop, instead of calling `table_len` separately. |
| check(2, options, true) | | local length |
| | | if options and options.dump then |
| local length = #seq
| | local i, item = 1, seq[1] |
| | | if item ~= nil then |
| if not options then
| | local dumped = {} |
| options = {}
| | repeat |
| end
| | dumped[i] = dump(item) |
| | | i = i + 1 |
| local conj
| | item = seq[i] |
| if length > 1 then
| | until item == nil |
| conj = options.conj or "and"
| | seq = dumped |
| if options.italicizeConj then
| |
| conj = "''" .. conj .. "''" | |
| end | | end |
| | length = i - 1 |
| | else |
| | length = table_len(seq) |
| end | | end |
|
| |
|
| Line 818: |
Line 297: |
| return "" | | return "" |
| elseif length == 1 then | | elseif length == 1 then |
| return seq[1] -- nothing to join | | return seq[1] |
| elseif length == 2 then
| |
| return seq[1] .. " " .. conj .. " " .. seq[2]
| |
| else
| |
| local comma = options.dontTag and "," or "<span class=\"serial-comma\">,</span>"
| |
| conj = options.dontTag and " " .. conj .. " " or "<span class=\"serial-and\"> " .. conj .. "</span> "
| |
| return concat(seq, ", ", 1, length - 1) ..
| |
| comma .. conj .. seq[length]
| |
| end | | end |
| end
| |
|
| |
|
| --[==[
| | local conj = options and options.conj |
| Concatenate all values in the table that are indexed by a number, in order.
| | if conj == nil then |
| * {sparseConcat{ a, nil, c, d }} => {"acd"}
| | conj = "and" |
| * {sparseConcat{ nil, b, c, d }} => {"bcd"}
| | end |
| ]==]
| |
| function export.sparseConcat(t, sep, i, j)
| |
| local list = {} | |
|
| |
|
| local list_i = 0 | | if length == 2 then |
| for _, v in export.sparseIpairs(t) do
| | return seq[1] .. " " .. conj .. " " .. seq[2] |
| list_i = list_i + 1 | |
| list[list_i] = v
| |
| end | | end |
|
| |
|
| return concat(list, sep, i, j) | | local punc, dont_tag |
| end
| | if options then |
| | | punc = options.punc |
| --[==[
| | if punc == nil then |
| Values of numeric keys in array portion of table are reversed: { { "a", "b", "c" }} -> { { "c", "b", "a" }}
| | punc = "," |
| ]==]
| | end |
| function export.reverse(t)
| | dont_tag = options.dontTag |
| checkType("reverse", 1, t, "table")
| | else |
| -- Not safe to use #t, as it can be unpredictable if there is a hash part.
| | punc = "," |
| local ret, base = {}, 0
| |
| repeat | |
| base = base + 1 | |
| until t[base] == nil
| |
| for i = base - 1, 1, -1 do
| |
| ret[base - i] = t[i]
| |
| end | | end |
| return ret
| |
| end
| |
|
| |
|
| function export.reverseConcat(t, sep, i, j)
| | local comma |
| return concat(export.reverse(t), sep, i, j) | | if dont_tag then |
| end
| | comma = "" -- since by default the serial comma doesn't display, when we can't tag we shouldn't display it. |
| | | conj = " " .. conj .. " " |
| --[==[
| | else |
| Invert an array. For example, {invert({ "a", "b", "c" })} -> { { a = 1, b = 2, c = 3 }}
| | comma = "<span class=\"serial-comma\">" .. punc .. "</span>" |
| ]==]
| | conj = "<span class=\"serial-and\"> " .. conj .. "</span> " |
| function export.invert(array)
| |
| checkType("invert", 1, array, "table")
| |
| | |
| local map = {}
| |
| for i, v in ipairs(array) do
| |
| map[v] = i
| |
| end | | end |
|
| |
|
| return map | | return concat(seq, punc .. " ", 1, length - 1) .. comma .. conj .. seq[length] |
| end | | end |
|
| |
|
| --[==[ | | --[==[ |
| Convert `list` (a table with a list of values) into a set (a table where those values are keys instead). This is a useful
| | A function which works like `table.concat`, but respects any `__index` metamethod. This is useful for data loaded via `mw.loadData`.]==] |
| way to create a fast lookup table, since looking up a table key is much, much faster than iterating over the whole list
| | function export.concat(t, sep, i, j) |
| to see if it contains a given value.
| | local list, k = {}, 0 |
| | |
| By default, each item is given the value true. If the optional parameter `value` is a function or functor, then the value
| |
| for each item is determined by calling it with the item key as the first parameter, plus any additional arguments passed
| |
| to {listToSet}; if value is anything else, then it is used as the fixed value for every item.
| |
| ]==] | |
| function export.listToSet(list, value, ...) | |
| checkType("listToSet", 1, list, "table")
| |
| local set, i = {}, 0 | |
| if value == nil then
| |
| value = true
| |
| elseif is_callable(value) then
| |
| -- Separate loop avoids an "is callable" lookup each iteration.
| |
| while true do
| |
| i = i + 1
| |
| local item = list[i]
| |
| if item == nil then
| |
| return set
| |
| end
| |
| set[item] = value(item, ...)
| |
| end
| |
| end
| |
| while true do | | while true do |
| i = i + 1 | | k = k + 1 |
| local item = list[i] | | local v = t[k] |
| if item == nil then | | if v == nil then |
| return set | | return concat(list, sep, i, j) |
| end | | end |
| set[item] = value | | list[k] = v |
| end | | end |
| end | | end |
|
| |
|
| --[==[ | | --[==[ |
| Return true if all keys in the table are consecutive integers starting at 1.
| | Add a list of aliases for a given key to a table. The aliases must be given as a table.]==] |
| ]==]
| |
| function export.isArray(t)
| |
| checkType("isArray", 1, t, "table")
| |
| | |
| local i = 0
| |
| for _ in pairs(t) do
| |
| i = i + 1
| |
| if t[i] == nil then
| |
| return false
| |
| end
| |
| end
| |
| return true
| |
| end
| |
| | |
| --[==[
| |
| Add a list of aliases for a given key to a table. The aliases must be given as a table. | |
| ]==] | |
| function export.alias(t, k, aliases) | | function export.alias(t, k, aliases) |
| for _, alias in pairs(aliases) do | | for _, alias in pairs(aliases) do |
| Line 940: |
Line 354: |
| end | | end |
|
| |
|
| return export | | local mt = {} |
| | |
| | function mt:__index(k) |
| | local submodule = safe_require("Module:table/" .. k) |
| | self[k] = submodule |
| | return submodule |
| | end |
| | |
| | return setmetatable(export, mt) |