Skip to content

table

A table is a data structure that is used to store values. A table is similar to an array or a map in other programming languages, but it can be used for a wide range of purposes, including arrays, maps, records, and objects.

Functions

string table.concat(table t, string sep, number i, number j)

ReturnsThe concatenated string.
Given a table where all elements are strings or numbers, returns table[i]..sep..table[i+1] ··· sep..table[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is the length of the table. If i is greater than j, returns the empty string.
  • t The table to concatenate.
  • sep The separator.
  • i The start index.
  • j The end index.
1
2
3
local animals = {"cat", "dog", "elephant", "giraffe", "horse"}
local animalString = table.concat(animals, "+", 2, 4)
print(animalString)   -- output: dog+elephant+giraffe

void table.insert(table t, number pos, table value)

ReturnsThe table self.
Inserts element value at position pos in table, shifting up other elements to open space, if necessary.
  • t The table.
  • pos The position to insert a value.
  • value The value to insert.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
local numbers = {1, 3, 5, 7, 9}
table.insert(numbers, 1, 0)
for i, num in ipairs(numbers) do
    print(i, num)
end
-- output:
1    0
2    1
3    3
4    5
5    7
6    9

number table.maxn(table t)

ReturnsThe largest positive numerical index.
Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (Performance Note: To do its job this function does a linear traversal of the whole table.)
  • t The table.

table table.remove(table t, number pos)

ReturnsThe removed value.
Removes from table the element at position pos, shifting down other elements to close the space, if necessary. Returns the value of the removed element.
  • t The table.
  • pos The position.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
local fruits = {"apple", "banana", "cherry", "date"}
local banana = table.remove(fruits, 2)
print("removed:", banana)
for i, fruit in ipairs(fruits) do
    print(i, fruit)
end
-- output:
removed:   banana
1   apple
2   cherry
3   date

void table.sort(table t, function comp<table, table, boolean>)

Sorts table elements in a given order, in-place, from table[1] to table[n], where n is the length of the table. If comp is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that not comp(a[i+1],a[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead.
  • t The table to sort.
  • comp The comp function.