I am designing a generic table filter which can remove entries from a given table, the problem is that keys are not unique to accomplish this and types are also different.
Let me elaborate more clearly with an example
SampleTable = {
{ key1 = 10, key2 = 'name_1', Str = 'sample_string_1' },
{ key1 = 10, key2 = 'name_3', Str = 'sample_string_2' },
{ key1 = 11, key2 = 'name_2', Mac = {'ID1', 'ID2', 'ID3'} },
{ key1 = 11, key2 = 'name_2', Mac = {'ID1'} },
{ key1 = 12, key2 = 'name_4', Mac = {'ID2', 'ID3'} }
}
function filter(inputTable, ...)
filterItems = {...}
end
I want to pass any number of keys to filter this table
local key1 = 11
local Mac = 'ID1'
filter(SampleTable, key1, Mac)
-- Should return -> { key1 = 11, key2 = 'name_2', Mac = 'ID1'},
key1 = 12
Mac = 'ID3'
filter(SampleTable, key1, Mac)
-- Should return -> { key1 = 12, key2 = 'name_4', Mac = ID3'}
key1 = 11
Mac = 'ID2'
filter(SampleTable, key1, Mac)
-- Should return both
-- { key1 = 11, key2 = 'name_2', Mac = ID2'},
-- { key1 = 11, key2 = 'name_5', Mac = ID2'},
key1 = 10
Str = 'sample_string_2'
filter(SampleTable, key1, Str)
-- Should return { key1 = 10, key2 = 'name_3', Str = 'sample_string_2'}
My current solution is search through each key,value pair in both tables
function filter(tIn, tFilter)
local retain = true
local exist = nil
local tOut = tIn
local _findInTable = function (t, k, v)
if(not t[k]) then return true
elseif(t[k] and t[k] == v) then return true
else return false end
end
for i, t in ipairs (tIn) do
for k,v in pairs (tFilter) do
exist = _findInTable(t, k, v)
retain = retain and exist
end
if not retain then tOut[i] = nil end
retain = true
end
return tOut
end
local myTable = filter(SampleTable, {key1 = 11, Mac = 'ID1'})
The problem is I cannot foresee how recursion will help.
This piece of code works when I have the following SampleTable, As you can see Mac is not a sub-table for my code.
SampleTable = {
{ key1 = 10, key2 = 'name_1', Str = 'sample_string_1' },
{ key1 = 10, key2 = 'name_3', Str = 'sample_string_2' },
{ key1 = 11, key2 = 'name_2', Mac = 'ID1' }
-- { key1 = 11, key2 = 'name_2', Mac = {'ID1', 'ID2', 'ID3'} },
-- { key1 = 11, key2 = 'name_2', Mac = {'ID1'} },
-- { key1 = 12, key2 = 'name_4', Mac = {'ID2', 'ID3'} }
}