How do I get all keys and values in as a flattened table from a nested table?

How do I get all keys and values in as a flattened table from a nested table?

Example:

nestedTable={
	world1={
		level1 = 15
	}
	world2={
		level1=10,
		level2=20
	}
}

getdetails(nestedTable)

--Will return:
{
{world1,level1,15},
{world2,level1,10}
{world2,level2,20}
}

I think something like this would work:

function getdetails(tbl)
	local flattened = {}
	
	for i,v in pairs(tbl) do
		if type(v) == "table" then
			for i2, v2 in pairs(v) do
				table.insert(flattened, {i, i2, v2})
			end
		else
			table.insert(flattened, {i, v})
		end
	end

	return flattened
end

accidentally pressed ctrl+enter while typing script before mb.
Nesting more tables into the nested tables will just leave the tables inside of the flattened table since I figured that was a bit more difficult to do (is possible though).

1 Like