Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Lua Table

Lua Table

table is a Lua data structure used to help us create different data types, such as arrays, dictionaries, etc.

Lua tables use associative arrays; you can use a value of any type as an array index, but that value cannot be nil.

Lua tables are not fixed in size; you can expand them as needed.

Lua also uses tables to handle 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 feature unique to Lua. The simplest constructor is {}, used to create an empty table. You can initialize an array directly:

-- Initialize the table

mytable

=

{

}

-- Assign values

mytable

[

1

]

=

"Lua"

-- Remove the reference

mytable

=

nil

-- Lua's garbage collection will free the memory

When we create table a and set elements, 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 table's elements. If no variable points to a, Lua's garbage collector will clean up the corresponding memory.

The following example demonstrates the situation described above:

Example

-- A simple table

mytable

=

{

}

print

(

"The type of mytable is "

,

type

(

mytable

)

)

mytable

[

1

]

=

"Lua"

mytable

[

"wow"

]

=

"Before modification"

print

(

"The element of mytable at index 1 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 element of alternatetable at index 1 is "

,

alternatetable

[

1

]

)

print

(

"The element of alternatetable at index wow is "

,

alternatetable

[

"wow"

]

)

alternatetable

[

"wow"

]

=

"After modification"

print

(

"The element of mytable at index wow is "

,

mytable

[

"wow"

]

)

-- Release the variable

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 execution result of the code above 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 the commonly used methods for table operations:

No. Method & Purpose
1 table.concat (table [, sep [, start [, end]]]):

concat is short for concatenate. The table.concat() function lists all elements of the array part of the specified table from the start position to the end position, with the elements separated by the specified separator (sep).

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

Insert an element with value value at the specified position (pos) in the array part of the table. The pos parameter is optional, defaulting to the end of the array part.

3 table.maxn (table)

Specify the largest key among all positive key values in the table. If no element with a positive key value exists, 0 is returned. (this method no longer exists after Lua 5.2; 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 shifted forward. The pos parameter is optional, defaulting to the table length, that is, deleting 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 the elements of a list:

Example

fruits

=

{

"banana"

,

"orange"

,

"apple"

}

-- Return the concatenated string of the table

print

(

"The concatenated string "

,

table.concat

(

fruits

)

)

-- Specify the separator character

print

(

"The concatenated string "

,

table.concat

(

fruits

,

", "

)

)

-- Specify indices to concatenate the table

print

(

"The concatenated string "

,

table.concat

(

fruits

,

", "

,

2

,

3

)

)

The output of the code above is:


连接后的字符串     bananaorangeapple
连接后的字符串     banana, orange, apple
连接后的字符串     orange, apple

Insertion and Removal

The following example demonstrates table insertion and removal operations:

Example

fruits

=

{

"banana"

,

"orange"

,

"apple"

}

-- 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

(

"The last element after removal is "

,

fruits

[

5

]

)

The output of the code above is:


索引为 4 的元素为     mango
索引为 2 的元素为     grapes
最后一个元素为     mango
移除后最后一个元素为     nil

Table Sorting

The following example demonstrates the use of the sort() method for sorting a table:

Example

fruits

=

{

"banana"

,

"orange"

,

"apple"

,

"grapes"

}

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 code above is:


排序前
1    banana
2    orange
3    apple
4    grapes
排序后
1    apple
2    banana
3    grapes
4    orange

Table Maximum Value

The table.maxn method no longer exists after Lua 5.2; we define a table_maxn method to implement it.

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

Example

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
(

"The maximum value of tbl: "

,

table_maxn

(

tbl

)

)

print

(

"The length of tbl "

,

tbl

)

The output of the code above is:


tbl 最大值:    34
tbl 长度     3

Note:

When we get the length of a table, whether using # or table.getn it will stop counting at the point where the indices are discontinuous, making it impossible to correctly obtain the table's length.

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