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