From 72c78db28ba926f06f6e9ddcfd9e3fe88e2bcff5 Mon Sep 17 00:00:00 2001 From: Jonathan Coates Date: Tue, 4 May 2021 18:05:56 +0100 Subject: [PATCH] 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 --- .../lua/rom/modules/main/cc/pretty.lua | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/main/resources/data/computercraft/lua/rom/modules/main/cc/pretty.lua b/src/main/resources/data/computercraft/lua/rom/modules/main/cc/pretty.lua index f202c204e..6ac9aeeb2 100644 --- a/src/main/resources/data/computercraft/lua/rom/modules/main/cc/pretty.lua +++ b/src/main/resources/data/computercraft/lua/rom/modules/main/cc/pretty.lua @@ -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