Is it possible to scan entire table?

Basically I just want to be able to scan an entire table much like Instance:GetDescendants() where it returns all the descendants just in the form where it scans a table

like:

local Tab = {}

for i,v in pairs(Tab) do
	print(v)
	if type(v) == "table" then
		for i2,v2 in pairs(v) do
			print(v2)
			if type(v2) == "table" then
				for i3,v3 in pairs(v2) do
						-- So on and so forth without having to be so sloppy
				end	
			end
		end	
	end
end

You are looking for a recursive solution, along the lines of:

local function recurseTable(tab)
   for i,v in pairs(tab) do
      if type(v) == "table" then
         recurseTable(v)
      else
         --Do things for non-table values
      end
   end
end

recurseTable(SomeTable)
5 Likes

You could use recursion to do this.

local function recursive_iter(t, fn)
    for key, value in pairs(t) do
        if type(value) == "table" then
            recursive_iter(value, fn)
        end
        fn(key, value)
    end
end

recursive_iter({ 0, 1, 2 }, print)
-->  1 0 2 1 3 2
recursive_iter( { 0, 1, { "a", "b" } }, print)
--> 1 0 2 1 1 a 2 b 3 table: 0xb80add1a65694ed5

Explanation

If it reaches a table value, the function calls itself recursively, so that it applies the function fn to the nested table as well.

1 Like

Solution given to @WoolHat for answering first. :slight_smile:

Big thanks to @incapaxx though.