English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Lua Table

Table is a data structure in Lua that helps us create different data types, such as: arrays, dictionaries, etc.

Lua tables use associative arrays, and you can use any type of value as the index of the array, but this value cannot be nil.

Lua tables are not fixed in size, and you can resize them according to your needs.

Lua also uses tables to solve modules (module), packages (package), and objects (Object). For example, string.format indicates using "format" to index the table string.

Table (table) construction

Constructors are expressions for creating and initializing tables. Tables are a powerful feature unique to Lua. The simplest constructor is {}, which is used to create an empty table. Arrays can be initialized directly:

-- Initialize table
mytable = {}
-- Specify value
mytable[1]= "Lua"
-- Remove reference
mytable = nil
-- Lua garbage collection will release memory

When we set elements for table a and then assign a to b, both a and b point to the same memory. If a is set to nil If b can also access the elements of table, then Lua's garbage collection mechanism will clean up the corresponding memory if no specified variable points to a.

The following examples demonstrate the description above:

-- Simple table
mytable = {}
print("The type of mytable is ", type(mytable))
mytable[1]= "Lua"
mytable["wow"] = "modified before"
print("The index of mytable is ", 1 The element is ", mytable[1])
print("The element of mytable at index wow is ", mytable["wow"])
-- alternatetable and mytable refer to the same table
alternatetable = mytable
print("The index of alternatetable is ", 1 The element is ", alternatetable[1])
print("The element of mytable at index wow is ", alternatetable["wow"])
alternatetable["wow"] = "modified"
print("The element of mytable at index wow is ", mytable["wow"])
-- Release variables
alternatetable = nil
print("alternatetable is ", alternatetable)
-- mytable can still be accessed
print("The element of mytable at index wow is ", mytable["wow"])
mytable = nil
print("mytable is ", mytable)

The result of the above code execution is:

The type of mytable is nil, table
The index of mytable is 1 The element is nil, Lua
The element of mytable at index wow is nil before modification
The index of alternatetable is 1 The element is nil, Lua
The element of mytable at index wow is nil before modification
The element of mytable at index wow is nil after modification
alternatetable is nil
The element of mytable at index wow is nil after modification
mytable is nil

Table Operations

The following lists the commonly used methods for Table operations:

Serial NumberMethod & Purpose
1table.concat(table [, sep [, start [, end]]]):

concat is the abbreviation of concatenate (linkage, connection). The table.concat() function lists all elements of the specified table from the start position to the end position in the parameters, separated by the specified separator (sep).

2table.insert(table, [pos,] value):

Insert an element with value value at position pos in the array part of the table. The pos parameter is optional, and the default is the end of the array part.

3table.maxn (table)

Specify the maximum key value of all positive keys in the table. If there is no element with a positive key value, it returns 0. (Lua5.2This method does not exist anymore, and this article uses a custom function to implement it.)

4table.remove (table [, pos])

Return a part of the table array located at position pos. The subsequent elements will be moved forward. The pos parameter is optional, and the default is the length of the table, which is from the last element.

5table.sort (table [, comp])

Sort the given table in ascending order.

Next, let's look at some examples of these methods.

Table Concatenation

We can use concat() to output a string formed by concatenating the elements of a list:

fruits = {"banana","orange","apple"}
-- Return the concatenated string of table
print("Concatenated string ",table.concat(fruits))
-- Specify the connection character
print("Concatenated string ",table.concat(fruits,", "))
-- Specify index to concatenate table
print("Concatenated string ",table.concat(fruits,", ", 2,3))

The output of the above code is as follows:

Concatenated string bananaorangeapple
Concatenated string banana, orange, apple
Concatenated string orange, apple

Insert and remove

The following examples demonstrate the insert and remove operations of table:

fruits = {"banana","orange","apple"}
-- Insert at the end
table.insert(fruits,"mango")
print("Index is 4 The element is ",fruits[4])
-- At index 2 Insert at the key
table.insert(fruits,2,"grapes")
print("Index is 2 The element is ",fruits[2])
print("The last element is ",fruits[5])
table.remove(fruits)
print("The last element after removal is ",fruits[5])

The output of the above code is as follows:

Index is 4 The element is mango
Index is 2 The element is grapes
The last element is mango
The last element after removal is nil

Table Sorting

The following example demonstrates the use of the sort() method, which is used to sort tables:

fruits = {"banana","orange","apple","grapes"}
Print "Unsorted"
for k, v in ipairs(fruits) do
        print(k, v)
end
table.sort(fruits)
Print "Sorted"
for k, v in ipairs(fruits) do
        print(k, v)
end

The output of the above code is as follows:

Unsorted
1    banana
2    orange
3    apple
4    grapes
Sorted
1    apple
2    banana
3    grapes
4    orange

Table Maximum Value

table.maxn in Lua5.2 This method no longer exists. We have defined the table_maxn method to achieve this.

The following example demonstrates how to get the maximum value from a table:

function table_maxn(t)
  local mn = nil;
  for k, v in pairs(t) do
    if(mn==nil) then
      mn = v
    end
    if mn < v then
      mn = v
    end
  end
  return mn
end
tbl = {[1] = 2, [2] = 6, [3] = 34, [26] =5}
print("tbl Maximum Value:", table_maxn(tbl))
print("tbl Length", #tbl)

The output of the above code is as follows:

tbl Maximum Value:    34
tbl Length     3

Note:

When we get the length of a table, whether using # or table.getn, both will stop counting at the index break point, resulting in an incorrect table length.

You can use the following methods instead:

function table_leng(t)
  local leng=0
  for k, v in pairs(t) do
    leng=leng+1
  end
  return leng;
end