Lua table
A table is a data structure in Lua that helps us create different data types, such as arrays, dictionaries, etc.
Lua tables use associative arrays. You can use values of any type as array indices, but this value cannot be nil.
Lua tables are not fixed in size; you can expand them as needed.
Lua also uses tables to solve modules, packages, and objects. For example, string.format means using "format" to index the table string.
Table Constructors
A constructor is an expression that creates and initializes a table. Tables are a powerful and unique feature of Lua. The simplest constructor is {}, which creates an empty table. Arrays can be initialized directly:
mytable = {}
-- Specify value
mytable[1]= "Lua"
-- Remove reference
mytable = nil
-- Lua garbage collection will free 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, b can still access the elements of the table. If no specified variable points to a, Lua's garbage collection mechanism will clean up the corresponding memory.
The following example demonstrates the situation described above:
Example
mytable = {}
print("The type of mytable is ",type(mytable))
mytable[1]= "Lua"
mytable["wow"] = "Before modification"
print("mytable element at index 1 is ", mytable[1])
print("mytable element at index wow is ", mytable["wow"])
-- alternatetable and mytable refer to the same table
alternatetable = mytable
print("alternatetable element at index 1 is ", alternatetable[1])
print("alternatetable element at index wow is ", alternatetable["wow"])
alternatetable["wow"] = "After modification"
print("mytable element at index wow is ", mytable["wow"])
-- Release variable
alternatetable = nil
print("alternatetable is ", alternatetable)
-- mytable can still be accessed
print("mytable element at index wow is ", mytable["wow"])
mytable = nil
print("mytable is ", mytable)
The output of the above code is:
mytable 的类型是 table mytable 索引为 1 的元素是 Lua mytable 索引为 wow 的元素是 修改前 alternatetable 索引为 1 的元素是 Lua alternatetable 索引为 wow 的元素是 修改前 mytable 索引为 wow 的元素是 修改后 alternatetable 是 nil mytable 索引为 wow 的元素是 修改后 mytable 是 nil
Table Operations
The following lists commonly used methods for Table operations:
| No. | Method & Purpose |
|---|---|
| 1 | table.concat (table [, sep [, start [, end]]]): concat is the abbreviation of concatenate (linking, joining). The table.concat() function lists all elements of the array part of the specified table in the parameters from the start position to the end position, separated by the specified separator (sep). |
| 2 | table.insert (table, [pos,] value): Inserts an element with the given value at the specified position (pos) in the array part of the table. The pos parameter is optional and defaults to the end of the array part. |
| 3 | table.maxn (table) Returns the largest key value among all positive key values in the specified table. If there is no element with a positive key value, returns 0. (After Lua 5.2, this method no longer exists. This article uses a custom function implementation.) |
| 4 | table.remove (table [, pos]) Returns the element at position pos in the array part of the table. Subsequent elements are moved forward. The pos parameter is optional and defaults to the length of the table, i.e., removal starts from the last element. |
| 5 | table.sort (table [, comp]) Sorts the given table in ascending order. |
Next, let's look at examples of these methods.
Table Concatenation
We can use concat() to output a string formed by concatenating elements in a list:
Example
-- Returns the concatenated string of the table
print("Concatenated string ",table.concat(fruits))
-- Specify the separator character
print("Concatenated string ",table.concat(fruits,", "))
-- Specify indices to concatenate the table
print("Concatenated string ",table.concat(fruits,", ", 2,3))
The output of the above code is:
连接后的字符串 bananaorangeapple 连接后的字符串 banana, orange, apple 连接后的字符串 orange, apple
Insertion and Removal
The following example demonstrates the insertion and removal operations of tables:
Example
-- Insert at the end
table.insert(fruits,"mango")
print("The element at index 4 is ",fruits[4])
-- Insert at the key with index 2
table.insert(fruits,2,"grapes")
print("The element at index 2 is ",fruits[2])
print("The last element is ",fruits[5])
table.remove(fruits)
print("After removal, the last element is ",fruits[5])
The output of the above code is:
索引为 4 的元素为 mango 索引为 2 的元素为 grapes 最后一个元素为 mango 移除后最后一个元素为 nil
Table Sorting
The following example demonstrates the use of the sort() method to sort a Table:
Example
print("Before sorting")
for k,v in ipairs(fruits) do
print(k,v)
end
table.sort(fruits)
print("After sorting")
for k,v in ipairs(fruits) do
print(k,v)
end
The output of the above code is:
排序前 1 banana 2 orange 3 apple 4 grapes 排序后 1 apple 2 banana 3 grapes 4 orange
Table Maximum Value
table.maxn no longer exists after Lua 5.2. We defined the table_maxn method to implement it.
The following example demonstrates how to get the maximum value in a table:
Example
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:
tbl 最大值: 34 tbl 长度 3
Other ExtensionsNote:
When we get the length of a table, whether using#ortable.getnit will stop counting at the point where the index is interrupted, resulting in an incorrect length of the table.
You can use the following method instead:
function table_leng(t) local leng=0 for k, v in pairs(t) do leng=leng+1 end return leng; end