Recursively delete empty table in Lua

I’m trying to create a function that can delete all empty subtable in a table. Take for example this table:

local icon = { ["track"] = "Dark Evangelism", ["duration"] = { ["minimum"] = { }, ["maximum"] = { } }, ["stack"] = { ["minimum"] = { ["enabled"] = 1, ["value"] = 5, }, ["maximum"] = { } }, }

I try to delete the empty subtables through these functions:

local function tlengtht(T) --because #table is not precise local count = 0 for \_ in pairs(T) do count = count + 1 end return count end local function clearEmptyTables(t) local visit = {} for k, v in pairs(t) do if type(v) == 'table' then table.insert(visit, v) end end if (tlengtht(t[k]) == 0) then t[k] = nil end for \_, each in ipairs(visit) do clearEmptyTables(each) end end

The second function can eliminate regularly the empty subtables “duration” key (“minimum” and “maximum”), but once you remove these empty subtables I can’t find a way to eliminate key “duration” itself: should become empty once eliminated those values.

Can you help me?

Hey perdon,

is there a reason why you try to clear all the subtables instead of just niling out the whole table and recreating it?

Mighty not be the most elegant way, but does it’s job :wink:

Unless you don’t know which subtables the whole table contains beforehand?

Give this a try perdon.  It first checks if the value is a subtable.  If it is it calls itself with the subtable as the argument.  On return if that subtable is empty the entry in the main table is nilled out.  

The check on the main table doesn’t occur until after all subtables have been processed.  If you’ve nilled all of them out already the main table will get nilled out too now that it’s also empty.

local function clearEmptyTables( t ) for k,v in pairs(t) do if type(v) == 'table' then clearEmptyTables( v ) if next( v ) == nil then t[k] = nil end end end end

Hey perdon,

is there a reason why you try to clear all the subtables instead of just niling out the whole table and recreating it?

Mighty not be the most elegant way, but does it’s job :wink:

Unless you don’t know which subtables the whole table contains beforehand?

Give this a try perdon.  It first checks if the value is a subtable.  If it is it calls itself with the subtable as the argument.  On return if that subtable is empty the entry in the main table is nilled out.  

The check on the main table doesn’t occur until after all subtables have been processed.  If you’ve nilled all of them out already the main table will get nilled out too now that it’s also empty.

local function clearEmptyTables( t ) for k,v in pairs(t) do if type(v) == 'table' then clearEmptyTables( v ) if next( v ) == nil then t[k] = nil end end end end