Reputation: 466
Considering all the json, xml formatters/beautifies out there, I’ve been unable to find one for Lua tables/arrays ?
The nuance here is that the output to beautify, is from what i believe is a widely used table/array dump
function - see below..
function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then
k = '"'..k..'"'
end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
What I’m thinking is something like this.
A table dumped looks like this.
{[1] = ,[2] = { ["attr"] = { [1] = code,[2] = remaining,[3] = resetdate,["remaining"] = 990,["resetdate"] = 1638614242,["code"] = 200,} ,["tag"] = success,} ,[3] = ,["attr"] = { } ,["tag"] = prowl,}
I’d love a beautifier that could present it like this..
{
[1] = ,
[2] = {
["attr"] = {
[1] = code,
[2] = remaining,
[3] = resetdate,
["remaining"] = 990,
["resetdate"] = 1638614242,
["code"] = 200,
} ,
["tag"] = success,
} ,
[3] = ,
["attr"] = { } ,
["tag"] = prowl,
}
Upvotes: 0
Views: 484
Reputation: 2205
An example of such processing, you can correct the little things yourself:
function dump(o,level)
level = level or 1
if type(o) == 'table' then
local s = {}
s[1] = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then
k = '"'..k..'"'
end
s[#s+1] = string.rep('\t',level).. '['..k..'] = ' .. dump(v, level+1) .. ','
end
s[#s+1] = string.rep('\t',level) .. '} '
return table.concat(s , "\n")
else
return tostring(o or 'nil')
end
end
local t = {[1] = nil,[2] = { ["attr"] = { [1] = code,[2] = remaining,[3] = resetdate,["remaining"] = 990,["resetdate"] = 1638614242,["code"] = 200,} ,["tag"] = success,} ,[3] = nil,["attr"] = { } ,["tag"] = prowl,}
print (dump(t))
result:
{
["attr"] = {
} ,
[2] = {
["attr"] = {
["remaining"] = 990,
["code"] = 200,
["resetdate"] = 1638614242,
} ,
} ,
}
you should also be aware that empty initialization values (like [3] =,) will throw an error, and generally zero data (like [3] = resetdate ) will be discarded in the dump, because assigning nil means deleting the table element.
Upvotes: 2