Question about tables

This has been on my mind for a while and I would like some clarification. Is there a proper way to destroy a table, or do you just set it equal to nil and every key in the table will be set to nil as well? Here is an example below:

local part = workspace.Part
local num = 10
local arr = {"1","2","3"}

local tab = {}
tab.part = part
tab.num = num
tab.arr = arr

--Which way is correct?
--Option 1
tab = nil

--Option 2
tab.part = nil
tab.num = nil
tab.arr = nil
tab = nil

My second question is does the code below copy the table or just makes a reference?

local part = workspace.Part
local num = 10
local arr = {"1","2","3"}

local tab = {}
tab.part = part
tab.num = num
tab.arr = arr

local newtab = tab --is this a copy of "tab" or a reference to "tab"

Numbers aren’t GC objects, so you can never leak memory with numbers. tab = nil will clear the reference to the table, and the part and arr lose a reference. The local variables still reference it though so once they go out of scope then they can be garbage collected when destroyed

a reference (print(newtab == tab))

2 Likes

Thanks, that clears that up. I have a final question shown here:

local part = workspace.Part

local tab = {}
tab.part = part
tab.touched = part.Touched:Connect(function()
	print("hi")
end)


--Will this automatically disconnect the connection
tab = nil

--Or do i need to do this first
tab.touched:Disconnect()
tab = nil

Yeah you will want to disconnect it first.

1 Like