Search code examples
classobjectlua

LUA delete all objects from a class


Need to iterate through all objects created by the following class and destroy them after they become useless;

Casing = {}
Casing.__index = Casing
sentArray = {}
function Casing.create(x, y, z)
    if x ~= nil and y ~= nil and z ~= nil then
        local _casing = {}
        setmetatable(_casing,Casing)
        --etc.
        return _casing
    end
end

Edit (answer):

The issue with this question is simple: There is no need to explicity deconstruct or destroy variables. Lua automatically destroys unused variables and dereferences them accordingly — as demonstrated and explained in the answer below.


Solution

  • Tables in Lua are subject to GC. Simply abandon all references when they become 'useless' and unless you've turned off garbage collection their 'destruction' will just happen naturally.

    An example of manually subjecting a table to GC:

    local mytable = {}
    
    print(mytable)
    print(collectgarbage('count'))
    
    mytable = nil
    
    collectgarbage()
    print(collectgarbage('count'))
    
    --[[stdout (approximation):
      table: 0x7fa821c066f0
      23.7412109375
      22.81640625
    ]]
    

    If you want to keep a record of the instances you create you can store references to them in a table. Simply removing them from the table will cause GC to clean them up, assuming no other references are held.

    Something naive like this:

    local my_instances = {}
    
    local function create_instance ()
        local t = {}
    
        my_instances[#my_instances + 1] = t
    
        return t
    end
    
    local function destroy_instances ()
        for i = 1, #my_instances do
            my_instances[i] = nil
        end
    end
    

    Alternatively, you can create a weak table, so you can operate on any instances that still have external references in your program. Once again, when all references outside of this table are lost, GC will kick in.

    local my_instances = setmetatable({}, {
        __mode = 'k'
    })
    
    local function create_instance ()
        local t = {}
    
        my_instances[t] = true
    
        return t
    end