Merge pull request #3 from aryajur/master

@aryajur Improved table encoding code to handle sparse arrays.
pull/44/head
alexandro-rezakhani 2021-06-04 11:46:17 -04:00 committed by GitHub
commit 43efcf7de4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 26 additions and 15 deletions

View File

@ -64,22 +64,31 @@ 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
local nLen = 0
for k,v in pairs(val) do
if (type(k) ~= "number" or k<=0) and not (k == "n" and type(v) == "number") then
array = nil
break -- Treat as object
else
if k > length then
length = k
end
if k == "n" and type(v) == "number" then
nLen = v
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
if nLen > length then
length = nLen
end
-- 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 +96,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 +119,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