How would I get rid of an OOP object?

So for example’s sake, within this code block:

local module = require(...)

local dictionary = {
	["VALUE1"] = module.new()
}

How would I properly dispose of the dictionary value, aside from setting it to nil? Or would that be the most efficient. Would I need to add a function to the object where it sets clears and freezes itself?

If that object has anything in itself that needs to be destroyed, I’d make a :Destroy method in it which cleans it up. Then, set the table to nil.

This article could help: How to remove a lua table entry by its key? - Stack Overflow

I was asking if this is the most efficient way?

   setmetatable(self, nil)
    table.clear(self)
    table.freeze(self)

You don’t need to set the metatable again. You don’t need to freeze the table either. Just set it to nil. Garbage collection will handle the rest.

1 Like

Yes, I believe this is. This will make self unusable, and everything in it.

Would it have any benefits if I did call a :Destroy() function before setting it to nil?

Depends on if that object has anything that needs to be manually removed. For example, if that object creates a UI, a model, etc. yeah, you’d want to make a destroy method to remove it. If all that object has is variables, like self.SomeVariable = 5, then you don’t need to make a destroy method. Setting the table to nil will work just fine.

There’s no garbage collection function in Luau. You would have to make your own or suffer from memory leaks.

What? Garbage collection is built into Lua, and Roblox utilizes this as well. Doesn’t matter if it’s Luau or Lua. Simply google “Roblox Garbage Collection”

Garbage collection runs in the background with the task scheduler. It’s automatic.

Garbage Collection and Memory Leaks in Roblox - What you should know - Resources / Community Tutorials - DevForum | Roblox

3 Likes

I believe they were referring to the fact that the collectgarbage function has been heavily sandboxed. Luau’s garbage collector is discussed in the following articles.