Search code examples
recursionluascopeluaxml

Lua declaring local variable in a recursive function


I just started programming and choosed lua to write a script that processes a XML configuration file.

I load the XML file with LuaXML (C binding version) which maps it to a heavily nested table.

My problem came up when I tried to write a function that finds all matches to a tag in the xmltable. The matches are inserted in a table that is returned by the function. My problem is with the declaration of this table variable, that has to be local to function.

First I tried:

local result = result or {}

But this declares the variable with every recursion.

Finally I came up with this solution that works, but seems too complicated to me:

function findall_wrapper(xmltable, tag)

  local results = {}

  function findall(xmltable, tag)

    if xml.TAG == tag then table.insert (results, xmltable) end

    for k, v in pairs(xmltable) do
      if (type(v) == "table") then findall(v, tag) end 
    end
  end

  findall(xmltable, tag)
  return results

end

How can I solve this in a nicer, more elegant way? Why does local result = result or {} declares the variable with every recursion?

Sorry if the answer to my question is too obvious but as I mentioned, I just started programming.


Solution

  • If you mean that you didn't want to use a wrapper function then I think you came remarkably close. Was this is the sort of thing you were aiming for?

    function findall(xmltable, tag, results)
        local results = results or {}
        if xmltable[xml.TAG] == tag then table.insert(results, xmltable) end
        for k, v in pairs(xmltable) do
          if type(v) == "table" then findall(v, tag, results) end
        end
        return results
    end