Improved table encoding code to handle sparse arrays. Floating point numbers are encoding improved.

pull/28/head
aryajur 2020-07-19 15:26:25 -07:00
parent dbf4b2dd2e
commit ad6ac0fd8e
1 changed files with 19 additions and 15 deletions

View File

@ -64,22 +64,24 @@ local function encode_table(val, stack)
if stack[val] then error("circular reference") end
stack[val] = true
-- Check whether to treat as a array or object
local array = true
local length = 0
for k in pairs(val) do
if type(k) ~= "number" or k<=0 then
array = nil
break -- Treat as object
else
if k > length then
length = k
end
end
end
if rawget(val, 1) ~= nil or next(val) == nil then
-- Treat as array -- check keys are valid and it is not sparse
local n = 0
for k in pairs(val) do
if type(k) ~= "number" then
error("invalid table: mixed or invalid key types")
end
n = n + 1
end
if n ~= #val then
error("invalid table: sparse array")
end
if array then
-- Encode
for i, v in ipairs(val) do
table.insert(res, encode(v, stack))
for i=1,length do
table.insert(res, encode(val[i], stack))
end
stack[val] = nil
return "[" .. table.concat(res, ",") .. "]"
@ -87,9 +89,11 @@ local function encode_table(val, stack)
else
-- Treat as an object
for k, v in pairs(val) do
--[[
if type(k) ~= "string" then
error("invalid table: mixed or invalid key types")
end
]]
table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
end
stack[val] = nil
@ -108,7 +112,7 @@ local function encode_number(val)
if val ~= val or val <= -math.huge or val >= math.huge then
error("unexpected number value '" .. tostring(val) .. "'")
end
return string.format("%.14g", val)
return tostring(val)
end