Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete all elements in a Lua table?

Tags:

lua

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?

like image 365
bob Avatar asked Sep 02 '25 14:09

bob


1 Answers

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.

like image 188
cbz Avatar answered Sep 05 '25 11:09

cbz