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={}
Share:
11,266
Josh
Author by

Josh

Updated on June 04, 2022

Comments

  • Josh
    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
    jpjacobs about 13 years
    If 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
    Alexander Gladysh about 13 years
    Please 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
    Alexander Gladysh about 13 years
    This replaces one table with another, not wipes its contents. (That being said, this is often the preferred way.)
  • Archinamon
    Archinamon about 13 years
    If 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.