Get all values from a table; even if they're inside an array

Dear developers, I’m Lucas.

I need help doing this operation:
I want to get all values from this table:

local Table = {
	["Animals"] = {"Cats", "Dogs", "Snakes"};
	["Names"] = {"Sophia", "Luke", "Mimi"};
	["Friends"] = {
		["Best Friends"] = {"Kate", "George"};
		["New Friends"] = {"You", "Thomas"};
	};
["Favorite Animal"] = "Cat"
}

I want to use a function like ‘Instance:GetDescendants()’ using tables as instance.


I also tried this:

for _, a in pairs(Table) do
	print(a)
end

So the values were printed to the output:

> table:0x52e165...
> table:0xd0fe58...
> Cat
> table:0xdebec4...

But it only printed the values (“Cat”) which were not inside another table.


I tried another solution:

local function GetChlidren(Object)
	pcall(function()
		for _, a in pairs(Object) do
			return a
		end
	end)
end
print(GetChlidren(Table))

But it returned a nil value.


I really need help with this. I’m getting tired of this error and searching for solutions :roll_eyes:.
All kind of support is welcome :relaxed::pray:t4:.

3 Likes
local data = {}
function internal_getTabDescendants(table)
    for i,v in pairs(table) do
        if type(v) == "table" then
            internal_getTabDescendants(v);
        else
            table.insert(data, v);
        end
    end
end

function getDescFromTable(table)
    data = {};
    internal_getTabDescendants(table);
    return data;
end

getDescFromTable(table);
11 Likes
function getDescendants(tb)
	local variables = {}
	local function loop(tb)
		for _, v in pairs(tb) do
			if type(v) == 'table'  then
				loop(v)
			else
				table.insert(variables, v)
			end
		end
	end
    loop(tb)
	return variables
end

If you want to print it you can just do

print(unpack(getDescendants(Table)))
2 Likes

Thank you so much! @Kacper.
I didn’t knew the function ‘type()’ existed :sweat_smile:.


Thank you for your help!!

2 Likes

Thank you so much @ur_famous!


I won’t never forget that. This is my first post… :smile:

2 Likes