'how to delete all elements in a Lua table?
How do I delete all elements inside a Lua table? I don't want to do:
t = {}
table.insert(t, 1)
t = {} -- this assigns a new pointer to t
I want to retain the same pointer to t, but delete all elements within t.
I tried:
t = {}
table.insert(t, 1)
for i,v in ipairs(t) do table.remove(t, i) end
Is the above valid? Or is something else needed?
Solution 1:[1]
Table elements insert and remove performance compare
The Table size count 10000000
[1] while and rawset
while #t ~= 0 do rawset(t, #t, nil) end
spent time = 0.677220
[2] next and rawset
for k in next, t do rawset(t, k, nil) end
spent time = 0.344533
[3] ipairs and rawset
for i, v in ipairs(t) do t[i] = nil end
spent time = 0.012450
[4] for, rawset
count = #t
for i=0, count do t[i]=nil end
spent time = 0.009308
Table elemnets insert
[1] table insert function
for i=0, 10000000 do table.insert(t, i, i) end
spent time = 1.0590489
[2] use #t
for i=0, 10000000 do t[#t+1] = i end
spent time = 0.703731
[3] for, rawset
for i=0, 10000000 do rawset(t, i, i) end
spent time = 0.100010
result.
Fastest remove : 4
Fastest insert : 3
Solution 2:[2]
easiest and most performant:
for k,v in pairs(tab) do tab[k]=nil end
What you suggest isn't usable: table.remove shifts the remaining elements to close the hole, and thus messes up the table traversal. See the description for the next function for more info
Solution 3:[3]
For a faster version that ignores the __pairs metamethod:
local next = next
local k = next(tab)
while k ~= nil do
tab[k] = nil
k = next(tab, k)
end
EDIT: As @siffiejoe mentions in the comments, this can be simplified back into a for loop by replacing the pairs call with its default return value for tables: the next method and the table itself. Additionally, to avoid all metamethods, use the rawset method for table index assignment:
for k in next, tab do rawset(tab, k, nil) end
Solution 4:[4]
#table is the table size and so if t = {1,2,3} then #t = 3
So you can use this code to remove the elements
while #t ~= 0 do rawset(t, #t, nil) end
You will go through the table and remove each element and you get an empty table in the end.
Solution 5:[5]
Change the variable to anything else and then back to a table, so then it is empty.
t = {1,2,3}
print(t[1]) -- 1
t = "Hello World"
print(t) -- Hello World
t = {}
print(t[1]) -- nil
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | jpjacobs |
| Solution 3 | |
| Solution 4 | meneldal |
| Solution 5 |
