Basically I have a memory leak in my game I think, but thats not the point here
This lead me to find out very confusssing things that are confussing me a lot on how lua works exactly
so basically i was reading a forum post about memory leaks and it stated this:
local MyName = "CCTVStudios"
local DictionaryTable = {
Entry = MyName
}
MyName = nil
print(DictionaryTable.Entry)
then it prints CCTVStudios right?
But isnt the table referencing the original value, shouldnt that mean if the original value was changed the table should say nil?
Does that means lua clones the data??? I am so confused
And something that confused me even more
local MyName = "CCTVStudios"
local MyPart = Instance.new("Part")
MyPart.Parent = workspace
local DictionaryTable = {
Entry = MyName,
RandomPart = MyPart
}
MyPart:Destroy()
print(DictionaryTable.RandomPart)
it prints:
This makes no sense the part isnt even existant anymore how is it able to print it out
Also this behavior replicates with variables
local MyName = "CCTVStudios"
local MyNameVariable = MyName
MyName = nil
print(MyNameVariable)
So does that means I should set everything to nil once im completely done using it???
Destroying a part does not remove it from existence, it simply sets the parent to nil, disconnects any events connected to the part, and locks the parent from being changed again. This applies to all instances. It is not removed from existence until there are no more references to it anywhere in the game, whether it be in your code, an object value, or as the property of another object.
Because your DictionaryTable still holds a reference to the part, destroying the part will not remove it from existence, it will just remove it from workspace. Once your DictionaryTable is garbage collected, which happens at the end of the current scope after the print, the part will no longer have any references to it and will also be garbage collected, actually removing it from existence.
Memory leaks in your game can be caused by infinitely adding values to a table and not ever deleting them, or connecting events and never disconnecting them or destroying the object that they are connected to. These are the two most common ways a memory leak can be created in Roblox. However, in this case your table is a local variable and will be deleted at the end of the scope. All the references in the table will also be dereferenced and garbage collected, so there is no memory leak here.
An example of a memory leak would be:
local playerSaveData = {}
game.Players.PlayerAdded:Connect(function(plr)
playerSaveData[plr.UserId] = {
coins = 100,
xp = 1000,
-- etc...
}
end)
This will add a new entry to a table every time a player joins a game, but will never delete those entries when the player leaves, making the table bigger and bigger as the server gets older.