Search code examples
lualua-table

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

  • 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.