Search code examples
lualua-table

Lua | Whitelist of table arguments only


I am trying to make a whitelist of allowed args so any provided args in the table that are not in my whitelist table are deleted from the args table.

local args = {
"99",
"lollypop",
"tornado",
"catid",
"CATID",
"filter_mediaType",
"one",
"10",
}

local args_whitelist = {
"beforeafter",
  "catid",
  "childforums",
  "display",
  "element_id",
  "element_type",
  "exactname",
  "filter_mediaType",
  "filter_order",
  "filter_order_Dir",
  "filter_search",
  "filter_tag",
  "format",
  "id",
  "Itemid",
  "layout",
  "limit",
  "limitstart",
  "messageid",
  "more",
  "option",
  "order",
  "ordering",
  "quality",
  "query",
  "recently",
  "recip",
  "reply_id",
  "return",
  "searchdate",
  "searchf",
  "searchphrase",
  "searchuser",
  "searchword",
  "sortby",
  "start",
  "task",
  "tmpl",
  "token",
  "view",
  "component",
  "path",
  "extension"
}

--[[
Do something here to eliminate and remove unwanted arguments from table
]]
--args[key] = nil --remove the argument from the args table

print(args) --[[ Output i want based of my whitelist of allowed arguments only

catid
filter_mediaType

]]

How can I make my code check the args table against my whitelist table and then run my delete function to remove the junk args from the args table.


Solution

  • I suggest altering your whitelist to allow for a simpler check. this can be done by inverting the table on run to allow for both fast check and easy of maintainability, as pointed out by Nicol Bolas.

    Inverting the table fills the whitelist table with numbers indexed by strings, allowing the check for the if statement to be a simply index of the value from args.

    You can then loop through the args list and check if the arg is on the whitelist. If it appears on the whitelist add the value to a new list, i will use approved in my example. after checking all the args you then set args = approved this cleans the table of any unapproved values.

    local args = {
    "99",
    "lollypop",
    "tornado",
    "catid",
    "CATID",
    "filter_mediaType",
    "one",
    "10",
    "beforeafter",
    }
    
    local function invert_table(target)
        local t = {}
        for k,v in pairs(target) do
            t[v] = k
        end
        return t
    end
    
    local args_whitelist = invert_table(args_whitelist)
    
    
    local approved = {}
    for _,v in pairs(args) do
        if args_whitelist[v] then
            approved[#approved + 1] = v
        end
    end
    args = approved