Table can't set itself to nil i.e. can't destroy itself

I’ve been messing around with OOP functionality and I’m trying to make a function similar to how Instance:Destroy() works.

local t = {}


function t:Destroy()
	self = nil
end

t:Destroy()
wait(3)

print(t)

The table should be destroying itself but it’s not. Are tables not supposed to set itself to nil?

1 Like

Why would you wanna be destroying a table ???

Oh yeah also, setting stuff to nil will not actually remove them, it’s just a bad way to overload memory

Each player gets a large table upon joining my game. I’m using the method/function to clean that large table up after they leave. It’s complicated to explain any more…

Setting self = nil doesn’t do anything because self is just like a parameter to a function, it’s just another reference. When you call a function with : the function presumes self is the first argument passed and handles all of that for you. What you should do in a custom Destroy is disconnect all events. To allow tables to be garbage collected, they must not exist in any scope of any function anymore. So you should set all references of the table to nil, but setting self to nil doesn’t do anything except remove that one reference.

More info on garbage collection:

(Though I don’t recommend doing what it says entirely, just some info on weak/strong references)

1 Like

You can’t set a whole table to nil, but you can set all the table descendants to nil or clear the table

Also, as said before, setting stuff to nil will not actually remove it.

1 Like

Doesn’t it get garbage collected to free up space though? The value of the variable I mean

nil just parents it to something different, setting values to nil will still use memory.

Example: Setting a part to nil will not remove it, only change it’s parent to an instance that can’t be seen without the use of exploits

1 Like