Reputation: 113
I want to clear a table but not sure which way is the best and does what different than each other. What are the differences among these:
tbl = {}
for k, v in pairs(tbl) do v = nil end
for k, v in pairs(tbl) do tbl[k] = nil end
Thanks.
Upvotes: 2
Views: 233
Reputation: 7056
tbl = {}
This doesn't so much clear the table as just create a new one. The old one might get garbage-collected, depengin on whether there are other references to it.
for k, v in pairs(tbl) do v = nil end
This does absolutely nothing. It's a waste of processing power.
for k, v in pairs(tbl) do tbl[k] = nil end
This actually empties the table without creating a new one. For small tables, this is often more performant than creating a new table, as it means less work for the GC, but that's a somewhat advanced optimization technique and it's not like clearing tables is always better.
Note that pairs
uses the next
function, which can handle keys being removed while iterating.
Upvotes: 4