table⚓︎
This library provides generic functions for table manipulation. It provides all its functions inside the table table.
Functions⚓︎
table.bininsert⚓︎
Inserts a given value through BinaryInsert into an array-style table t, assuming t was sorted by comp.
If 'comp' is given, then it must be a function that receives two values in t and returns true when the first is less than the second.
i.e., comp(a,b) == true would mean a is less than b.
If you want to sort in reverse order, you may set comp = function(a, b) return a > b end.
This function will return the index where value was inserted into t.
local result = table.bininsert(t, value, comp)
Parameters:
t(valueType[])value(valueType)comp(fun(a: valueType, b: valueType): boolean): Optional.
Returns:
result(number)
table.binsearch⚓︎
Performs a binary search for a given value inside a specified array-style table tbl.
If the value is in tbl, then its corresponding index will be returned. Otherwise, this function will return nil.
If findAll == true, then this binsearch will return the lowest and highest indices that store value. (These indices will be equal if there is only one copy of value in tbl.)
You can optionally provide a comp function. If provided, binsearch will treat tbl as if it had been sorted by table.sort(tbl, comp).
local index, highestMatch = table.binsearch(tbl, value, comp, findAll)
Parameters:
tbl(valueType[])value(valueType): The value to search for.comp(fun(a: valueType, b: valueType): boolean): Optional. The function used to sorttbl. If not provided, then the standard<operator will be used.findAll(boolean): Default:false. If true,
Returns:
index(integer, nil): Anindexsuch thattbl[index] == value, if such an index exists.nilotherwise. IffindAll == true, this will be the smallest index such thattbl[index] == value.highestMatch(integer, nil): If a match was found, and iffindAll == true, then this will be the largestindexsuch thattbl[index] == vale.nilotherwise.
table.calleventhandlers⚓︎
Calls event handlers in reverse order until one returns false.
local eventHandled = table.calleventhandlers(handlers, ...)
Parameters:
handlers((fun(...): boolean?)[]): The event handlers to call....(any): Arguments passed to each handler.
Returns:
eventHandled(boolean): True if no further handlers should be called.
table.callmultipleeventhandlers⚓︎
Calls arrays of event handlers until one group handles the event.
local eventHandled = table.callmultipleeventhandlers(handlers, ...)
Parameters:
handlers((fun(...): boolean?)[][]): The handler groups to call....(any): Arguments passed to each handler.
Returns:
eventHandled(boolean): True if no further handler groups should be called.
table.choice⚓︎
Returns a random element from the given table.
local value, key = table.choice(t)
Parameters:
t({ [keyType]: valueType })
Returns:
value(valueType): The randomly chosen value.key(keyType): The table key of the chosen value.
table.clear⚓︎
This clears all keys and values from a table, but preserves the allocated array/hash sizes. This is useful when a table, which is linked from multiple places, needs to be cleared and/or when recycling a table for use by the same context. This avoids managing backlinks, saves an allocation and the overhead of incremental array/hash part growth.
Please note this function is meant for very specific situations. In most cases it's better to replace the (usually single) link with a new table and let the garbage collection do its work.
table.clear(table)
Parameters:
table(table): The table to clear.
table.contains⚓︎
Returns true if a value is contained in a table t, and false otherwise.
local result = table.contains(t, value)
Parameters:
t(table)value(unknown)
Returns:
result(boolean)
table.copymissing⚓︎
Copies a table's contents from one table to another, including subtitles. If a non-table key is already defined, it will not be overwritten. Metatables are not copied.
table.copymissing(to, from)
Parameters:
to(table)from(table)
table.deepcopy⚓︎
Copies a table's contents. All subtables will also be copied, as will any metatable.
local result = table.deepcopy(t)
Parameters:
t(tableType)
Returns:
result(tableType)
table.deeptostring⚓︎
Recursively converts a value to a human-readable string.
local result = table.deeptostring(value, level, prefix)
Parameters:
value(any)level(integer): Default:1. The maximum recursion depth.prefix(string): Optional. The current indentation prefix.
Returns:
result(string)
table.empty⚓︎
Checks if a table is empty.
This is a compatibility helper that uses pairs and therefore respects normal iteration behavior such as __pairs. By contrast, table.isempty is a lower-level rubic0n helper that inspects raw table storage and does not honor __pairs or readonly proxy backing storage.
If deepCheck == true, then tables are allowed to have nested subtables, so long as those subtables are empty. e.g., table.empty({ {}, {} }, true) == true, while table.empty({ {}, {} }) == false. Use table.isempty when you specifically need a raw-storage emptiness check.
local result = table.empty(t, deepCheck)
Parameters:
t(table)deepCheck(boolean): Default:false. Iftrue, subtables will also be checked to see if they are empty.
Returns:
result(boolean)
table.filter⚓︎
Creates a new table that results from using f to filter out elements of t. i.e., table.filter(t,f) will consist of only the pairs k, v of t for which f(k, v) was not false or nil.
Any additional arguments will be passed to f. For example, table.filter(t, f, 10) would call f(k, v, 10) on each pair k, v of t.
Warning
Do not use this function on array-style tables, as it will not shift indices down after filtering out elements. Instead, you should use table.filterarray on array-style tables.
local result = table.filter(t, f, ...)
Parameters:
t({ [keyType]: valueType })f(fun(k: keyType, v: valueType, ...): boolean): The function to use when filtering values oft. (This is sometimes called a predicate function.)...(any): Additional parameters to pass tof.
Returns:
result({ [keyType]: valueType }): The result of usingfto filter out elements oft.
table.filterarray⚓︎
Creates a new array-style table that results from using f to filter out elements of an array-style table arr. i.e., table.filterarray(arr, f)
will consist of only the pairs i, v of arr for which f(i, v) was not false or nil.
Any additional arguments will be passed to f. For example, table.filterarray(arr, f, 10) would call f(i, v, 10) on each value pair i, v of arr.
When an element gets filtered out, the index of subsequent items will be shifted down, so that the resulting table plays nicely with the # operator and the ipairs function.
local result = table.filterarray(arr, f, ...)
Parameters:
arr(valueType[])f(fun(i: integer, v: valueType, ...): boolean): The function to use when filtering values oft. (This is sometimes called a predicate function.)...(any): Additional parameters to pass tof.
Returns:
result(valueType[]): The result of usingfto filter out elements oft.
table.find⚓︎
Returns the key for a given value, or nil if the table does not contain the value.
local key = table.find(t, value)
Parameters:
t({ [keyType]: valueType })value(valueType)
Returns:
key(keyType, unknown, nil): Akeysuch thattbl[key] == value, if such a key exists.nilotherwise.
table.findminscore⚓︎
Finds the array element with the lowest score returned by scoreFn.
local element, score, index = table.findminscore(array, scoreFn)
Parameters:
array(valueType[])scoreFn(fun(x: valueType): number, nil)
Returns:
element(valueType, nil): The element with the lowest score.score(number, nil): The lowest score.index(integer, nil): The index of the element with the lowest score.
table.get⚓︎
Gets a value in a table. If the key doesn't exist in the table, a specified default value will be returned instead.
local result = table.get(t, key, defaultValue)
Parameters:
t({ [keyType]: valueType })key(keyType): The key to use to access the table.defaultValue(defaultValueType): The default value if the key didn't exist in the table.
Returns:
result(valueType, defaultValueType, unknown)
table.getorset⚓︎
Gets a value in a table. If the key doesn't exist in the table, a specified default value will be set in the table and returned instead.
local result = table.getorset(t, key, defaultValue)
Parameters:
t({ [keyType]: valueType })key(keyType): The key to use to access the table.defaultValue(defaultValueType): The default value to set and return if the key didn't exist in the table.
Returns:
result(valueType, defaultValueType, unknown)
table.getprintabletable⚓︎
Returns a printable multi-line representation of a table-like value.
local result = table.getprintabletable(inputTable, maxDepth, indentStr, indentLevel)
Parameters:
inputTable(table, userdata)maxDepth(integer): Default:50.indentStr(string): Optional. Defaults to a tab character.indentLevel(integer): Default:0.
Returns:
result(string)
table.gettablefromcommasplit⚓︎
Splits a comma-separated string into a table.
local result = table.gettablefromcommasplit(inputString)
Parameters:
inputString(string)
Returns:
result(string[])
table.gettablefromsplit⚓︎
Splits a string using a Lua pattern. If the pattern has captures, the first capture from each match is stored; otherwise, the full match is stored.
local result = table.gettablefromsplit(inputString, pattern)
Parameters:
inputString(string)pattern(string)
Returns:
result(string[])
table.invert⚓︎
Returns a copy of t with the keys and values flipped.
local result = table.invert(t)
Parameters:
t({ [keyType]: valueType })
Returns:
result({ [valueType]: keyType })
table.isarray⚓︎
Returns true when the given Lua table is a pure array-like Lua table, or false otherwise.
local result = table.isarray(t)
Parameters:
t(table)
Returns:
result(boolean)
table.isempty⚓︎
Returns true when raw table storage has no non-nil values.
This low-level helper inspects raw table storage directly. It does not honor __pairs, readonly proxy backing storage, or table.makereadonly backing contents.
local result = table.isempty(t)
Parameters:
t(table)
Returns:
result(boolean)
table.isequal⚓︎
Recursively compares tables by key/value equality without recursing forever on cycles.
Tables are structurally compared with raw table identity checks. Table __eq metamethods are not invoked for table identity or table values. Non-table values use normal Lua equality.
local result = table.isequal(left, right)
Parameters:
left(any)right(any)
Returns:
result(boolean)
table.keys⚓︎
Returns an array-style table of all keys in the given table, t. Optionally, it will sort the returned table.
local keys = table.keys(t, sort)
Parameters:
t({ [keyType]: unknown }): The table to get keys for.sort(boolean, fun(a: keyType, b: keyType): boolean): Optional. If true, the returned table will be sorted. If a function is passed, the table will be sorted using the given function.
Returns:
keys(keyType[]): An array of all table keys.
table.makereadonly⚓︎
Returns a proxy that guards normal assignment through the returned table.
This protects normal assignment on the proxy or converted tables, but it is not a sandbox boundary against rawset, debug-library metatable or upvalue access, or hostile privileged code. Omitting copy converts the input table in place and rehomes raw entries behind backing storage.
local result = table.makereadonly(inTable, copy, strict)
Parameters:
inTable(tableType)copy(boolean): Default:false. Copy instead of converting in place.strict(boolean): Optional. Throw when reading missing keys.
Returns:
result(table): The readonly table proxy.
table.map⚓︎
Creates a new table consisting of key value pairs k, f(k, v), where k, v is a pair in t.
Any additional arguments will be passed to f. For example, table.map(t, f, 10) would call f(k, v, 10) on each value v of t.
local result = table.map(t, f, ...)
Parameters:
t({ [keyType]: valueType })f(fun(k: keyType, v: valueType, ...): newValueType): The function to apply to each element oft....(any): Additional parameters to pass tof.
Returns:
result({ [keyType]: newValueType }): The result of applyingfto each value int.
table.mapfilter⚓︎
Maps an array through scoreFn, keeping values with non-false scores.
local output, scores = table.mapfilter(array, scoreFn)
Parameters:
array(valueType[])scoreFn(fun(x: valueType): scoreType, nil)
Returns:
output(valueType[])scores(scoreType[])
table.mapfiltersort⚓︎
Maps and filters an array, then sorts by the returned scores.
local output, scores = table.mapfiltersort(array, scoreFn)
Parameters:
array(valueType[])scoreFn(fun(x: valueType): number, nil)
Returns:
output(valueType[])scores(number[])
table.new⚓︎
This creates a pre-sized table. This is useful for big tables if the final table size is known and automatic table resizing is too expensive.
local newTable = table.new(narray, nhash)
Parameters:
narray(number): A hint for how many elements the array part of the table will have. Allocates fields for [0, narray].nhash(number): A hint for how many elements the hash part of the table will have.
Returns:
newTable(table): The pre-sized table that was created.
table.print⚓︎
Prints the result of table.getprintabletable(inputTable, ...).
table.print(inputTable, maxDepth, indentStr, indentLevel)
Parameters:
inputTable(table, userdata)maxDepth(integer): Optional.indentStr(string): Optional.indentLevel(integer): Optional.
table.removevalue⚓︎
Removes a value from a given list. Returns true if the value was successfully removed.
local result = table.removevalue(list, value)
Parameters:
list({ [unknown]: valueType })value(valueType)
Returns:
result(boolean)
table.shallowcopy⚓︎
Shallow-copies values from one table to another table.
local result = table.shallowcopy(from, to)
Parameters:
from(fromType)to(toType): Optional.
Returns:
result(fromType, toType)
table.shuffle⚓︎
Shuffles the table in place using the Fisher-Yates algorithm. Passing in table size as the second argument saves the function from having to get it itself.
table.shuffle(t, n)
Parameters:
t(table)n(integer): Default:#t. The length of the array.
table.size⚓︎
Returns the number of elements inside the table. Unlike the length operator (#) this will work with any table.
local result = table.size(t)
Parameters:
t(table)
Returns:
result(number)
table.sortedpairs⚓︎
Returns an iterator over keys in sorted order.
local iterator = table.sortedpairs(tbl, comparator)
Parameters:
tbl({ [keyType]: valueType })comparator(fun(a: keyType, b: keyType): boolean): Optional.
Returns:
iterator(fun(): keyType, valueType)
table.swap⚓︎
Sets a value in a table and returns any previously defined value for that key.
local oldValue = table.swap(t, key, value)
Parameters:
t({ [keyType]: valueType })key(keyType): The key to use to access the table.value(any): The value to set.
Returns:
oldValue(valueType, unknown, nil): The previously defined value att[key].
table.traverse⚓︎
This function performs a DFS over a graph-like table. You can specify the key of the subtable that contains the child nodes.
Each "node" is an object with a children table of other "nodes", each of which might have their own children. For example, a sceneNode is made up of niNodes, and each niNodes can have a list of niNode children. This is best used for recursive data structures like UI elements and sceneNodes etc.
local iterator = table.traverse(t, k)
Parameters:
t(tableType): A table to transverse.k(string): Default:children. The subtable key.
Returns:
iterator(fun(): tableType, any)
Example: Iterate over all scene nodes attached to player.
In the example below, function onLoaded() will be called when the game has been successfully loaded.
For each scene nodes attached to the player, its type (node.RTTI.name) and name (node.name), will be printed to MWSE.log.
local function onLoaded()
mwse.log("Player's scene graph:")
for node in table.traverse({ tes3.player.sceneNode }) do
mwse.log("%s : %s", node.RTTI.name, node.name)
end
end
event.register(tes3.event.loaded, onLoaded)
table.unwind⚓︎
Unpacks all values from an object iterable with pairs.
local values = table.unwind(object)
Parameters:
object(table)
Returns:
values(any)
table.unwindarray⚓︎
Unpacks all values from an object iterable with ipairs.
local values = table.unwindarray(object)
Parameters:
object(table)
Returns:
values(any)
table.values⚓︎
Returns an array-style table of all values in the given table, t. Optionally, it will sort the returned table.
local values = table.values(t, sort)
Parameters:
t({ [unknown]: valueType }): The table to get values for.sort(boolean, fun(a: valueType, b: valueType): boolean): Optional. If true, the returned table will be sorted. If a function is passed, the table will be sorted using the given function.
Returns:
values(valueType[]): An array of all table values.
table.wrapindex⚓︎
This function is used for calculating relative access into an array, such that accessing an element one past the array's size will instead return the position of the first element. Providing an index one before the start (note that this is 0, not -1) will instead give the index to the last element in the array.
local index = table.wrapindex(t, index)
Parameters:
t(table): The table whose size will determine the new wrapped index.index(number): The initial provided index. If this is before or after the array, it will be cycled around.
Returns:
index(number)