Garbage collecting functions

  1. What do you want to achieve?
    I want a way for functions to be set to nil after all of the strong references to it have been removed
  2. What is the issue?
    I have a function that references no variables outside of its scope and i have a table that has its metatable set to another table with __mode = “kv”. I then set the variable to nil, meaning that theres only one weak reference to it, the one in the table. Using this logic, tables, variables and instances have all been automatically collected by the garbage collector after a few seconds and the table’s reference to the variable has been set to nil. The only time it hasnt worked is on a function.
  3. What solutions have you tried so far?
    Considering theres not that many resources, i’ve checked all of the large garbage collection topics and a bunch of smaller ones but none of them mention garbage collecting functions. The only thing i’ve seen mentioning it is one thread saying that once a function has no external references, it gets garbage collected but that should still occur in my script and remove the function, but it doesnt.
    Few other things thats worth mentioning, i’ve tried running the function at all points, if i run it after its set to nil, it errors, if i run it before then it runs but the whole garbage collection stuff doesnt change. Also, when the function is printed in the table it prints “function” but when its printed with a direct reference (e.g print(TestTest)it prints the UUID, idk if that has anything to do with it.
local Class = {}
Class.__index = Class

local TestTest = function()
	print(123)
end

function Class.new() 
	return setmetatable({
		Variables = setmetatable({
			[1] = TestTest
		},{__mode = "kv"}),	
	},Class)
end

function Class:Run()
	task.wait(3)
	TestTest = nil
	print("Set Nil", self) -- Should return {Variables = {[1] = function}}
	task.wait(3)
	print("GC wait",self) -- Should return {Variables = {}} - Actually returns the same as above
end

return Class

Heres the code that runs the module

task.wait(1)
local ClassHandler = require(script.Handler)
local Class = ClassHandler.new()
Class:Run()

Again, might just be me being stupid and you dont need to do this at all but i have a similar system for tables and thought functions would be somewhat similar. Thanks for any help.

1 Like

Still couldn’t get it to work, only thing i could do is put the function in a table but im not sure this A) properly stops the function from potentially having memory leaks B) is the proper way to use lua’s garbage collection.

Code changes

local TestTest = {function()
	print(123)
end,}

For anyone looking at this in the future, my only reccomendation is to make sure the function doesnt reference anything outside of its scope and store things you want automatically collected in a table and then put that in the metatable (i really am not sure though).

If you have a response for this in the future i’d appreciate it!