I use Penlight’s pretty-print module. It has the added benefit that you can save the output to a file and load it back to recreate the table that you output.
You can find the module here:
https://github.com/stevedonovan/Penlight/blob/master/lua/pl/pretty.lua
Penlight’s module has some dependencies on some other modules, so if you want something smaller you can use the following code from stdlib’s base.lua:
-- @func tostring: Extend tostring to work better on tables
-- @param x: object to convert to string
-- @returns
-- @param s: string representation
\_G.\_tostring = tostring -- make original tostring available
local \_tostring = tostring
function \_G.tostring (x)
return render (x,
function () return "{" end,
function () return "}" end,
\_tostring,
function (t, \_, \_, i, v)
return i .. "=" .. v
end,
function (\_, i, \_, j)
if i and j then
return ","
end
return ""
end)
end
-- @func prettytostring: pretty-print a table
-- @t: table to print
-- @indent: indent between levels ["\t"]
-- @spacing: space before every line
-- @returns
-- @s: pretty-printed string
function \_G.prettytostring (t, indent, spacing)
indent = indent or "\t"
spacing = spacing or ""
return render (t,
function ()
local s = spacing .. "{"
spacing = spacing .. indent
return s
end,
function ()
spacing = string.gsub (spacing, indent .. "$", "")
return spacing .. "}"
end,
function (x)
if type (x) == "string" then
return string.format ("%q", x)
else
return tostring (x)
end
end,
function (x, i, v, is, vs)
local s = spacing .. "["
if type (i) == "table" then
s = s .. "\n"
end
s = s .. is
if type (i) == "table" then
s = s .. "\n"
end
s = s .. "] ="
if type (v) == "table" then
s = s .. "\n"
else
s = s .. " "
end
s = s .. vs
return s
end,
function (\_, i)
local s = "\n"
if i then
s = "," .. s
end
return s
end)
end
to use the above, place one or both in your code then
print(tostring(sometable))
print(prettytostring(sometable))
[import]uid: 846 topic_id: 10480 reply_id: 40147[/import]