-4
Let’s assume I have a table that stores information on 200 tables,
local rand = math.random;
--[=[
- Uma tabela que armazena uma informação
- sobre tabelas específicas
- (Cada campo contém uma chave que referencia uma tabela,
- e um valor sendo um número randômico de 0 à 50, por exemplo:
- tables[ {} ] = rand(0, 50))
]=]
tables = {};
-- Armazena um número randômico para uma tabela
local function init(t)
tables[t] = rand(0, 50);
end
for i = 1, 2e2 do
init {};
end
It looks okay, but the table referenced by tables
, in the end, it receives 200 fields that, together, reference 200 tables that needed to be collected by garbage collector moon.
Q: 200 fields? Each one references a table?
A: See the loop and the callinit {}
. A table is being declared and referenced in the first argument of the referenced function ininit
. This function defines a field intables
, its key being the table of the first argument of the call, and its value being a random number. That is, the defined field key references a table.Q: Why the 200 declared tables needed to be collected and why they could not be collected?
A: Because they will not be recognized by my program. The 200 tables in this case have nothing to do with the program. Imagine if they were tables instantiated by a class. This class could have a table that stores private data for its instances. For this, each field of this table contains a key that references the instance (respectively a table), and the value of each field equals the data of its instances. But what if this private data table is preventing that instances (respectively tables) are collected by the Moon’s trash? For example, a case where the private data table is the only one that is referencing a certain table and still storing its data. The intention is that these unique tables referenced within the private data table be collected as garbage.
While the table referenced by tables
is not collected as garbage by the Moon, 200 unused tables will not be collected as well. In this example code the program will finish running and the table will probably be collected as garbage by the Moon, but this is not the goal, as said, is a example, The real situation wouldn’t be like this. In the real situation, the program will continue running (and asynchronously) until it is stopped for some time.
Is there any way to make the unique tables referenced by table fields tables
be collected as garbage by the Moon in this case? I also wondered if this is possible only in versions of the Moon, larger than 4.0.