Doubt with cleaning a table

I got a table with some connections inside:

local Connecs = {}

And i want to clean it:

for _,Connec in ipairs(Connecs) do
    Connec:Disconnect()
    Connec = nil
end

Does this clean the table properly? I’m unsure.

Connec is just a local variable inside the loop, so setting it to nil doesn’t affect the table. You can remove that line and instead do table.clear(Connecs) after the loop finishes.

4 Likes

Only use table.clear if you’re going to reuse that table after cleaning it up since it will keep the capacity of the table’s array part to avoid expensive rehashes whenever a new entry is added (this is assuming your Connecs table is an array as you’re using ipairs to loop through it). If you just want to clean the array and never use it again, you can do so the proper way as follows:

for key, Connec in ipairs(Connecs) do
    Connec:Disconnect()
    Connecs[key] = nil
end