Remove data from table in Lua
There are two ways to remove data in a table
Method 1: Press the mark to remove
table.remove(table_name, [pos,])
Directly remove the data of a subscript, for example :
local t = {5, 6, 7, 8}
table.remove(t, 2)
for k, v in pairs(t) do
print(k, v)
end
Output:
remove an item of data in pairs
local t = {5, 6, 7, 8}
for k, v in pairs(t) do
if k == 2 then
table.remove(t, 2)
end
end
for k, v in pairs(t) do
print(k, v)
end
Output result:
Method 2: Leave a value blank
table[k] = nil
directly empty a value
local a = {
['3019'] = 3019,
['3020'] = 3020,
['3021'] = 3021,
['3017'] = 3017
}
a['3019'] = nil
for k, v in pairs(a) do
print(k, v)
end
Output result:
empty an item in pairs
local a = {
['3019'] = 3019,
['3020'] = 3020,
['3021'] = 3021,
["3017"] = 3017,
}
for k,v in pairs(a) do
if k == '3019' then
a[k] = nil
end
end
for k, v in pairs(a) do
print(k,v)
end
Output result: