Correctly handle sparse arrays in cc.pretty

This also swaps the order we display mixed array/maps in, so that the
array part comes first. I think this is more sensible.

Closes #777
This commit is contained in:
Jonathan Coates 2021-05-04 18:05:56 +01:00
parent 53dd15a213
commit cf0f67265f
2 changed files with 20 additions and 7 deletions

View File

@ -409,18 +409,24 @@ local function pretty_impl(obj, options, tracking)
local doc = setmetatable({ tag = "concat", n = 1, space_line }, Doc)
local length, keys, keysn = #obj, {}, 1
for k in pairs(obj) do keys[keysn], keysn = k, keysn + 1 end
for k in pairs(obj) do
if type(k) ~= "number" or k % 1 ~= 0 or k < 1 or k > length then
keys[keysn], keysn = k, keysn + 1
end
end
table.sort(keys, key_compare)
for i = 1, keysn - 1 do
for i = 1, length do
if i > 1 then append(doc, comma) append(doc, space_line) end
append(doc, pretty_impl(obj[i], options, tracking))
end
for i = 1, keysn - 1 do
if i > 1 or length >= 1 then append(doc, comma) append(doc, space_line) end
local k = keys[i]
local v = obj[k]
local ty = type(k)
if ty == "number" and k % 1 == 0 and k >= 1 and k <= length then
append(doc, pretty_impl(v, options, tracking))
elseif ty == "string" and not keywords[k] and k:match("^[%a_][%a%d_]*$") then
if type(k) == "string" and not keywords[k] and k:match("^[%a_][%a%d_]*$") then
append(doc, text(k .. " = "))
append(doc, pretty_impl(v, options, tracking))
else

View File

@ -177,7 +177,7 @@ describe("cc.pretty", function()
end)
it("displays mixed tables", function()
expect(pretty({ n = 3, 1, 2, 3 })):eq("{ n = 3, 1, 2, 3 }")
expect(pretty({ n = 3, 1, 2, 3 })):eq("{ 1, 2, 3, n = 3 }")
end)
it("escapes keys", function()
@ -191,6 +191,13 @@ describe("cc.pretty", function()
it("groups tables", function()
expect(pretty({ 1, 2, 3 }, 4)):eq("{\n 1,\n 2,\n 3\n}")
end)
it("handles sparse tables", function()
local tbl = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
tbl[4] = nil
expect(tostring(pp.pretty(tbl))):eq("{ 1, 2, 3, nil, 5, 6, 7, 8, 9, 10 }")
end)
end)
it("shows numbers", function()