Visualizing Tables

I use tables alot, and wanted to know if there is any other way other than printing your tables, to see the contents of a table and the contents of its sub tables if it has any etc.

By this I’m assuming you just mean print(table)?

There’s really no way to visualize a table without printing its contents.

A simple way to visualize a table is to do print(unpack(table)). For example:

local myTable = {1, 2, 3}
print(unpack(myTable))
-- Output >> 1 2 3

If a table can have subtables, then you can loop through the table and unpack the index if it is another table. For example:

local myTable = {
	1,
	{2, 3},
	4,
}
local function visualizeTable(tbl) -- works for dictionaries as well
	for index, content in ipairs(tbl) do
		if type(content) == "table" then
			print(index, "-", unpack(content))
		else
			print(index, "-", content)
		end
	end
end
visualizeTable(myTable)
--[[
Output:
1 - 1
2 - 2 3
3 - 4
--]]

If subtables can have their own subtables, then you need to add a bit of recursion, unpacking each of the tables. It can get a bit complicated to have it visualize neatly when you have to deal with multiple subtables, so I won’t get into that here. Hopefully what I’ve given you is enough.

2 Likes

Here is a recursive function that prints tables with indenting to help indicate sub-tables.

local printTable -- declare beforehand for recursion purposes
printTable = function(t, s)
	s = s or 0
	print(string.rep("\t", s).."{")
	for i, v in pairs(t) do
		if (typeof(v) ~= "table") then
			print(string.rep("\t", s + 1).."["..tostring(i).."]: "..tostring(v))
		else
			print(string.rep("\t", s + 1).."["..tostring(i).."]:")
			printTable(v, s + 1)
		end
	end
	print(string.rep("\t", s).."}")
end
4 Likes

If you’re using the new expressive output beta, you should be able to just print a table directly.

Alternatively, you could always use Repr to print the table until the new output window releases.

2 Likes