Module:TableTools/doc
![]() | This is a documentation subpage for Module:TableTools. It may contain usage information, categories and other content that is not part of the original module page. |
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.
Loading the module
To use any of the functions, first you must load the module.
local TableTools = require('Module:TableTools')
isPositiveInteger
TableTools.isPositiveInteger(num)
This function returns true if num
is a positive integer, and false if not. Although it doesn't operate on tables, it is included here as it is useful for determining whether a given table key is in the array part or the hash part of a table.
getUnion
local union = TableTools.getUnion(t1, t2, ...)
This returns the union of the values of n tables, as an array. For example, for the tables {1, 3, 4, 5, foo = 7}
and {2, bar = 3, 5, 6}
, getUnion will return {1, 2, 3, 4, 5, 6, 7}
.
getIntersection
local intersection = TableTools.getIntersection(t1, t2, ...)
This returns the intersection of the values of n tables, as an array. For example, for the tables {1, 3, 4, 5, foo = 7}
and {2, bar = 3, 5, 6}
, getIntersection will return {3, 5}
.
getNumKeys
local nums = TableTools.getNumKeys(t)
This takes a table t
and returns an array containing the numbers of any numerical keys that have non-nil values, sorted in numerical order. For example, for the table {1, nil, 2, 3, foo = 'bar'}
, getNumKeys will return {1, 3, 4}
.
getAffixNums
local nums = TableTools.getAffixNums(t, prefix, suffix)
This takes a table t
and returns an array containing the numbers of keys with the optional prefix prefix
and the optional suffix suffix
. For example, the following code will return {1, 3, 6}
.
TableTools.getAffixNums({a1 = 'foo', a3 = 'bar', a6 = 'baz'}, 'a')
compressSparseArray
TableTools.compressSparseArray(t)
This takes an array t
with one or more nil values, and removes the nil values while preserving the order, so that the array can be safely traversed with ipairs. Any keys that are not positive integers are removed. For example, for the table {1, nil, foo = 'bar', 3, 2}
, getNumKeys will return {1, 3, 2}
.
sparseIpairs
TableTools.sparseIpairs(t)
This is an iterator function for traversing a sparse array t
. It is similar to ipairs, but will continue to iterate until the highest numerical key, whereas ipairs may stop after the first nil
value. Any keys that are not positive integers are ignored.
Usually sparseIpairs is used in a generic for
loop.
for i, v in TableTools.sparseIpairs(t) do
-- code block
end
Note that sparseIpairs uses the pairs
function in its implementation. Although some table keys appear to be ignored, all table keys are accessed when it is run.