问题
Let us see the following codes.
do
local a = {1,2,3}
function a:doSth()
self = nil
end
a:doSth()
if a then
print("Still has a...")
end
end
I found that this method doesn't work. The table a
still exists. Why?
I know the a = nil
can reclaim the memory which table a
holds.
How to directly get the memory holds by the table a
and free the memory just like delete
in C++?
回答1:
function a:doSth()
self = nil
end
Is syntax sugar for
function a.doSth(self)
self = nil
end
Your above code, there are two different references to the table value {1,2,3}
, one is through local a
, the other is through self
inside the function. nil
ing out one of the references doesn't change the other reference to the table.
For that table to be considered for gc collection, you have to make sure no references point to it. For example:
function a:doSth()
a = nil
end
That will release the reference by a
, there is still a reference from self
but that automatically goes out of scope when the function ends. After the function call, {1,2,3}
will get collected by the gc on the next cycle assuming nothing else refers to that table.
回答2:
You can do this:
a = nil
collectgarbage()
However I don't recommend running a full garbage collection cycle just to liberate 1 table. Garbage collection takes time and it is better to leave Lua to run it when it sees fit.
来源:https://stackoverflow.com/questions/28061733/how-to-delete-a-table-in-lua