Iterate through nested table

I don’t have a use case for this yet, but I want to know whether there’s a way to traverse all elements in a nested table, without using two functions in this way:

  local nested = {key = {
                  "str";
                   value = {
                          value2 = {"val"; 
                                   value3 = {"value"}
     							   }
                           }
                        }
                 }

  local function iter(tab)
        for k, v in pairs(tab) do
        if typeof(v) ~= "table" then print(v) 
        else
        loop(v)
       end
     end
  end

  function loop(t)
           for _, v in pairs(t) do
           if typeof(v) ~= "table" then print(v) 
      else
           iter(v) 
        end
     end
  end  
  
  loop(nested)

Let’s say you have a table like this:

local MyTable = {
    Name = "Joe",
    Money = 14,
    OwnedItems = {
        Axe = {ItemHealth = 14},
        Sword = {ItemHealth = 140}
    },
    UnlockedLocations = {"Snow","Desert","Forest"}
}

To iterate through it, you would need to write a function that recursively iterates through the table (known as recursion), like so:

local TabLevel = 0
local function PrintTable(Table)
    for Key,Value in pairs(Table) do
        if typeof(Value) == "table" then
	        TabLevel = TabLevel + 1
	        print(string.rep("    ",TabLevel - 1)..Key.." : {")
            PrintTable(Value)
            print(string.rep("    ",TabLevel - 1).."}")
            TabLevel = TabLevel - 1
        else
            print(string.rep("    ",TabLevel)..Key,Value)
        end
    end
end

So if I wanted to print all the contents of the example table provided, this is what the script would look like:

local MyTable = {
    Name = "Joe",
    Money = 14,
    OwnedItems = {
        Axe = {ItemHealth = 14},
        Sword = {ItemHealth = 140}
    },
    UnlockedLocations = {"Snow","Desert","Forest"}
}

local TabLevel = 0
local function PrintTable(Table)
    for Key,Value in pairs(Table) do
        if typeof(Value) == "table" then
	        TabLevel = TabLevel + 1
	        print(string.rep("    ",TabLevel - 1)..Key.." : {")
            PrintTable(Value)
            print(string.rep("    ",TabLevel - 1).."}")
            TabLevel = TabLevel - 1
        else
            print(string.rep("    ",TabLevel)..Key,Value)
        end
    end
end

PrintTable(MyTable)

Running the code above would spit this output:

  Money 14
  UnlockedLocations : {
      1 Snow
      2 Desert
      3 Forest
  }
  Name Joe
  OwnedItems : {
      Sword : {
          ItemHealth 140
      }
      Axe : {
          ItemHealth 14
      }
  }
3 Likes