FANDOM


This module finds the length of an array, or of a quasi-array with keys such as "data1", "data2", etc. It uses a [[binary search algorithm]] to find the length, so as to use as few table lookups as possible.
 
This algorithm is useful for arrays that use metatables (e.g. [[mw:Extension:Scribunto/Lua reference manual#frame.args|frame.args]]) and for quasi-arrays. For normal arrays, just use the [[mw:Extension:Scribunto/Lua reference manual#Length operator|# operator]], as it is implemented in [[C (programming language)|C]] and will be quicker.
 
Also, if you need to access every item in the array, it will be more efficient to load all of the data into a normal array and either use a counter variable or the # operator to find the length. This algorithm only makes sense when you only need to access a small subset of the array values. 
 
Finally, this algorithm should only be used on arrays containing around 10 or more items, as otherwise it will perform more table lookups than there are items in the array.
 
== Usage ==
 
First, load the module. It returns a function, <var>arrayLength</var>, although you may choose a different name.
 
<source lang="lua">
local arrayLength = require('Module:Array length')
</source>
 
The <var>arrayLength</var> function takes the following parameters:
 
<source lang="lua">
arrayLength(t, prefix)
</source>
 
* <var>t</var> is the array or quasi-array to find the length of. (table, required)
* <var>prefix</var> is the prefix for quasi-arrays. For example, a quasi-array with keys such as "data1", "data2", etc. would have the prefix "data". (string, optional)
 
It always returns a number. That number is either a positive integer or zero.
 
<includeonly>{{#ifeq:{{SUBPAGENAME}}|sandbox | |
<!-- Categories below this line, please; interwikis at Wikidata -->
[[Category:Lua metamodules]]
}}</includeonly>

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.