Formatting table exactly as the Roblox expressive output display does

The problem

print({
    Name = "John",
    Age = 18
})

returns

  hh:mm:ss.mil   table: 0x123456789abcdef = {
                    ["Age"] = 18,
                    ["Name"] = "John"
                 }

but

print(tostring({
    Name = "John",
    Age = 18
}))

returns

  hh:mm:ss.mil   table: 0x123456789abcdef

that.

How do I make a custom tostring function that exactly matches the roblox expressive output display (minus the collapsible triangle), and why isn’t this a built in feature yet??? I feel like I’m going ever so slightly insane every time I encounter this problem.

you could use the __tostring metamethod. if you don’t know what metatables and metamethods are, you can read my post here and here

local tbl = {
    Name = "John",
    Age = 18
}

local metatable = {
    __tostring = function(self)
        local stringed = [[{
]]
    
        for key, value in pairs(self) do
        stringed ..= string.format([[    [%s] = %s,
]], tostring(key), tostring(value))
        end
        stringed ..= "}"
        
        return
    end
}

print(tostring(tbl))
-- RESULT:
{
    ["Name"] = John,
    ["Age"] = 18,
}
-- NOTE: RESULT MAY VARY

I’ve made a function that converts the table it self and the tables inside it to string

local function FormatTable(t)
	local str = "{\n"
	
	for i,v in t do
		if type(v) == "table" then
			str ..= `	{i} = {string.gsub(FormatTable(v),"\n","\n	")}\n`
		else
			str ..= `	{i} = {tostring(v)}\n`
		end
	end
	
	return str .. "}"
end

local t = {
	Apple = 3,
	Number = "Hello",
	Test = {
		Boolean = true,
	}
}

print(FormatTable(t))
1 Like

Yes, but I’m pretty sure I don’t want or need a metatable on {1, 2, 3}.

Also, your solution doesn’t seem to handle nested arrays at all. Still, thank you for your contribution.

Hmm, with some tinkering I think I can get this to work. Thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.