Let's say I have a table that stores information about 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 seems okay, but the table referenced by tables
, in the end, gets 200 fields that together refer 200 tables that needed to be collected by the garbage collector of the Moon.
Q: 200 fields? Did each reference a table?
A: View the loop and callinit {}
. A table is being declared and referenced in the first argument of the function referenced 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 did the 200 declared tables need to be collected and why could they 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 holds private data for its instances. To do this, each field in this table contains a key that references the instance (respectively a table), and the value of each field is equivalent to the data of its instances. But what if this private data table is preventing instances (tables ) of that class from being collected by the Lua's garbage? For example, a case where the private data table is the only one that is referencing a certain table and still saving its data. The intention is that these single tables referenced within the private data table are collected as junk.
As long as the table referenced by tables
is not garbage collected by the Moon, 200 unused tables will not be collected as well. In this example code the program will finish executing and the table will probably be collected as garbage by the Moon, but that is not the purpose, as said, it is an example , the real situation would not be this way . In the real situation, the program will continue to run (and asynchronously) until it is stopped for any occasion.
Is there any way to make the unique tables referenced by the fields of the tables
table be garbage collected by the Moon in this case? I also wanted to know if this is only possible with versions of the Moon, larger than 4.0.