class=”markdown_views prism-atom-one-dark”>
Remove data in table in Lua
There are two ways to remove data from the table
Method 1: Press the mark to remove
table.remove(table_name, [pos,])
Directly remove a subscript data, for example:
local t = {
5, 6, 7 , 8}
table.remove(t, 2)
for k, v in pairs(t ) do
print(k, v)
end
Output result:
Remove a certain item from pairs item data
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 set a value to nothing
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 one in pairs item
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: