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))