how to delete all elements in a Lua table?

bob picture bob · Feb 2, 2011 · Viewed 47.8k times · Source

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?

Answer

cbz picture cbz · Feb 2, 2011
for k in pairs (t) do
    t [k] = nil
end

Will also work - you may have difficulty with ipairs if the table isn't used as an array throughout.