I’m making a party module where a function is party:Destroy(). Parties are tables.
I think the only way is to remove all references and let it get garbage collected, but the module’s user would still have a reference to the table in an other script. To destroy it, the user would have to call party:Destroy() and set all their references to nil.
Internally I can easily remove all references to the table, but the user’s references in other scripts are the problem.
Could you not just clear all the keys/indexes in the table??
Not sure I understand, are you like caching multiple references to numerous different tables? Because theoretically if you just have one table pointer, the next time you do something related to the party module (like to get a new party) that table pointer is replaced with a new one to the new table, and all your old references are gone at that point so the old table is eligible for garbage collection.
I could clear the table (which I already do), but that means the user’s references would point to an empty table and not nil.
Example scenario:
local party = PartyService:CreateParty()
--all parties have a reference to them in PartyService.Parties, it's like a storage for all parties
party:Destroy() --removes references like the one in PartyService.Parties and clears table
--party would be {} and not nil because in this script is still a reference (the party variable)
To destroy the party, I’d have to set party = nil.
I don’t necessarily see that being a problem though. If you’re using one pointer in the global scope, you could just overwrite that when a new party is made.
I’d also assume all your empty table references would clean up at some point depending on when it pops off the stack, which is essentially when code execution finishes.
e.g:
local function x()
--//Push table pointer onto the stack
local party = PartyService:CreateParty()
--//Table reference pops off the stack, and that table is eligible for garbage collection
end
x()
Alternate solution:
You could implement some RemoteEvents to handle setting table pointers to nil when it receives a request on the client to do so.
Could be a solution to just overwrite the not longer needed references, but this opportunity doesn’t arise often.
That’s true and I actually don’t mind having an empty table instead of nil, but I thought it would be nice to be able to do things like if not party then or if party == nil then.
Unfortunately the module can only be used on the server.
And actually, you’d think that’d work, but it won’t. Each table is its own object, so you’re essentially comparing one table object with another table object, and they’re not the same, so it’ll return false.
Kind of like how in OOP each object you create from a class is its own unique object.