How to wipe or reset a table in Lua
11,266
Solution 1
You iterate over the keys and make them nil.
for k,v in pairs(t) do
t[k] = nil
end
If it's an array then remove values with table.remove()
Solution 2
What about this way?
t = {..some non-empty table..}
...some code...
t={}
Author by
Josh
Updated on June 04, 2022Comments
-
Josh almost 2 years
How would I go about completely wiping or resetting a table in Lua. I want to make it into a blank table in the end.
-
jpjacobs about 13 yearsIf using remove, start removing at the end of the array, otherwise it will take a long time, as all elements after the created hole need to be moved. The approach using
pairs
is much faster. -
Alexander Gladysh about 13 yearsPlease note that, while this will work for most of the tables, it is possible to craft a table which would not be cleaned in this way, using metatables.
-
Alexander Gladysh about 13 yearsThis replaces one table with another, not wipes its contents. (That being said, this is often the preferred way.)
-
Archinamon about 13 yearsIf no more vars linked to target's table - then gc will delete it from memory and will create a new table with a new physical address. Else nulling every element useing loop is the best thing.