Game Development Reference
In-Depth Information
table.insert ( aTable, [pos,] value )
This function is used to insert a value into the array table, as indicated by aTable . The value is
inserted at the position indicated by pos ; if no value is indicated for pos , then it is assigned the
default value of the length of the table plus 1 (i.e., at the end of the table).
local aryTable = {1, 3, 4, 5}
table.insert(aryTable, 2, 2)
print(table.concat(aryTable, ",")
table.insert(aryTable, 6)
print(table.concat(aryTable, ",")
1 that the # operator returns the length of an array, but only of a contiguous section. So, if
#
table.maxn , on the other hand,
print(#aryTable, table.maxn(aryTable))
table.remove ( aTable [, pos] )
This function is like insert , but with the difference that it removes an element from the array table and
returns the element being removed. In both insert and remove , the elements are shifted to accommodate
the new index as required. The default position for pos is the length of the table (i.e., the last element).
local aryTable = {1, 2, 3, 4, 5}
table.remove(aryTable, 2, 2)
print(table.concat(aryTable, ",")
table.remove(aryTable)
print(table.concat(aryTable, ",")
print(aryTable[3])
table.sort ( aTable [, comp] )
This function is very useful when working with a series of values that need to be sorted. When no
comp is specified, it uses the standard > Lua operator to compare two values, which works fine with
numeric values. However, there could be situations where you might need to sort multidimensional
arrays or arrays that contain non-numeric data. For such cases, the comp function is used. comp
receives two table elements and returns true when the first is less than the second.
 
Search WWH ::




Custom Search