This my method to collect and clear a table, could this be improved or is it better off itself?
function __collectgc(t)
xpcall(function(...)
for k,v in t do
if typeof(v) == "RBXScriptConnection" then
v:Disconnect()
end
k = nil
v = nil
end
end, function(a0)
print(a0)
end)
end
If I may ask, why use protected calls? You have the necessary type check in place, making sure the object is in fact a script connection.
A second minor overlook are lines 7 and 8. Setting k and v returned by the iterator to nil will not have any impact over the table.
local part = Instance.new("Part")
local connectionList = {
part:GetPropertyChangedSignal("Name"):Connect(function() end);
"Just an innocent attempt to cause some trouble";
part:GetPropertyChangedSignal("Color"):Connect(function() end);
}
function __clearconnections(t)
for k,v in t do
if typeof(v) == "RBXScriptConnection" and v.Connected then
v:Disconnect()
end
end
table.clear(t)
end
__clearconnections(connectionList)
print(connectionList) --> {}
Caveats
table.clear() preserves allocated memory.
The proper way to clean a table and cause a change in preserved space is using t[k] = nil.
Disposing the old table by assigning a new one is an alternative, but I prefer the above two points.
Nevertheless! Setting a key or index to nil isn’t detected in order to improve assignment performance. That means assigning nil doesn’t shrink the table size until some non-nil elements are inserted to cause a rehash (which creates space allowing for more elements to be added).