Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What would be the best way to clear a table?

Asked by 7 years ago

I'm attempting to clear a table inside a function, but every-time I do, it either says I can't insert into the table because it's nil or it just adds the same record over and over again without clearing it.

Methods I have tried

Table = nil

^ is the one that says I can't insert into the table because it's nil

Table = {}

^ Doesn't clear the table, just keeps the records

1 answer

Log in to vote
0
Answered by 7 years ago
Edited 7 years ago

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()

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 meta-tables

Also, 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.

Ad

Answer this question