Worried About Event Table Garbage Collection

I have a module script that allows me to create tables that store a value and other things.
There is an event for each table that fires when the value is changed.
However, I’m worried that it might cause a memory leak, because every time a new table is created, a new event is added to a table that stores all of those events.
However, after doing some checks, it appears that the size of the events table keeps adding up every time I create a new table.

local TableEvents = {}

local function module:CreateTable(DefaultValue)	
	local Table = {
		Value = DefaultValue
	}
	
	TableEvents[Table] = Instance.new("BindableEvent")
	return Table
end

I thought about giving each table a unique name, like “Settings_Controls_Interact” and simply changing the value of the index in TableEvents to the new bindable event.

In short, every time I create a table, a new event is added to the table that stores all of the other table events.
When the player resets, I want the table’s event to be garbage collected.

Example:

When the player character loads, a new table is created to hold the player’s currently equipped item.
When they reset, the script that uses the table is destroyed and replaced with a new one, and it creates a new table for the equipped item.

Should I even be worried about this?
Is there a way to fix it?
Thanks for reading :slight_smile:

3 Likes

You should have a module:DestroyTables function which loops through all the table in TableEvents and destroys the bindable event. Whenever you want the player to reset call the function (or just call it player.CharacterAdded). Alternatively you can have a Name parameter while assigning the table.

local function module:CreateTable(Name, DefaultValue)
	local Table = {
		Value = DefaultValue
	}

    if TableEvents[Name] then TableEvent[Name].Event:Destroy(); TableEvent[Name].Table = nil end
	
	TableEvents[Name] = {
        Event = Instance.new("BindableEvent"),
        Table = Table,
    }

	return Table
end
5 Likes

Aha, so assigning names is the solution. Thank you!

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.