Will the memory be clogged in this case?

For example, we have functions or loops that use local variables and after they complete, what happens to the created variable? Will it clog up memory or will the garbage collector remove it?

for _, Item in workspace:GetChildren() do
	local Temp = Item
	Temp.Name = "a3"
end

What happens to the Temp variable after the loop ends? Will it be deleted or will it clog up memory?


One more example

local function Clone(Object)
	local ObjectVar = Object:Clone()
	Object.Parent = workspace
end

In this case, will the variable be deleted automatically or do I need to do it myself by assigning nil to the variable?

In the first example there doesn’t seem to be the need to store the Item inside of a variable since you can simply do:

for _, Item in workspace:GetChildren() do
	Item.Name = "a3"
end

There isn’t a memory-leak risk since Temp will be automatically set to nil once the for loop has concluded unless a strong reference to the variable is held, although you’ll be doing an un-necessary allocation

In the second example ObjectVar will be automatically set to nil after the function has finished running, which also depends to whether a strong reference is held to it

An example of a strong reference is if you use or reference the variable inside of a connection, which in that case would only be set to nil after the connection is disconnected

Thank you! Aren’t variables inside the connection deleted in the same way as in the example above?

If the variable is local to that connection’s scope then yes, it will be set to nil after the function is ran. If the variable is in an outside scope then it won’t be set to nil otherwise you’ll run into problems with scripts breaking after the garbage collector is ran. As an example, here the message variable will be set to nil after the onTouched function is ran due to it being local to its scope:

local part = script.Parent

local function onTouched(otherPart)
	local message = "Hello!"

	print(message)
end

part.Touched:Connect(onTouched)

But in this case message won’t turn to nil unless part.Touched is disconnected (technically in this example since message is in the global scope, it will never turn to nil unless you manually set it to nil anyway):

local part = script.Parent

local message = "Hello!"

local function onTouched(otherPart)
	print(message)
end

part.Touched:Connect(onTouched)

Edit: This is a better example than the one right above:

local function configurePart(part)
	local message = "Hello!"

	part.Touched:Connect(function()
		print(message)
	end)
end

configurePart(script.Parent)

Even after the configurePart function is successfully ran, message won’t turn to nil due to being a strong reference, even though it’s local to its scope