What are weak tables? [closed]

-7

What are weak tables (weak tables) in version 5.0 Moon? When to use them?

    
asked by anonymous 16.01.2017 / 14:16

1 answer

9

What you want to do does not need a weak reference. If the code is that, it will execute something and shut down, you do not have to do anything for the memory to be released.

If you want to create the table and have it destroyed shortly, put it in a local variable. Even if you have to go from one function to another, do it with local variables. When no variable is accessing the table, it can be destroyed. Local variables care invalidate the reference immediately o the GC will collect the object in the next step.

Using weak reference you have no control over the content, in the first collection the data may no longer exist and if you try to access it will have problems, so using weak reference is an error.

To use something global and have control over the lifetime you need to do manually.

A generic response under documentation , but remember that this should only be used when you can run out of the data at any time, even before using them.

a = {}
b = {}
setmetatable(a, b)
b.__mode = "v"
tabela = {}
a[1] = tabela
tabela = {}
a[2] = tabela
collectgarbage()
for k, v in pairs(a) do print(v) end

See running on ideone . Also put it on GitHub for future reference .

The v mode assigned with setmetatable makes the table values as weak references that is what you want. The letter k does the same with the keys.

    
16.01.2017 / 14:47