There are two ways to delete the table element in Lua:
1. assign a fieldNil
2. UseTable. Remove (table, index)
The following describes two methods:
1 Table. Remove
Let's take a look at the function prototype of this library function:
Table. Remove (table, POS)
@ Table: the table to be deleted.
@ Pos: the position of the table element to be deleted. This parameter is optional. If this parameter is not specified, the default value is the table length, that is, the last element of the table is deleted.
local t = {10, 20, 30, 40,50, 60}
table.remove(t, 3)
for k,v in pairs (t) do
print("t", k, v)
end
Result:
We can see that 3rd elements 30 cannot be found!
In addition, we can also see that the following 40, 50, and 60 move forward one
Therefore, do not use table. Remove () multiple times in the loop. If you must use it, test it with caution!
2 value: Nil
The following code is used as an experiment environment.
local t =
{
[10] = 1,
[20] = 2,
[30] = 3,
[40] = 4,
[50] = 5,
[60] = 6
}
If table. Remove () is used, the position of POS is hard to find, because the non-array sorting in Lua is based on the hash value.
It may be convenient to assign a value of nil to a table structure that is hard to find in POS,
Suppose I want to delete T [30],
Only
t[30] = nil
for k,v in pairs (t) do
print("t", k, v)
end
Result:
We can see that t [30], 3 is not found.
Of course, assigning a value to nil is not only used to delete table elements, but can be used to delete any variable!
From Weizhi note (wiz)
Delete a Lua table element