encoder: Break apart the encoder into distinct modules + add call encoding
[luajson.git] / src / json / encode / array.lua
blob6b75bce3d619eb063c5fd153de6020f66d0661b6
1 local jsonencode = require("json.encode")
3 local type = type
4 local pairs = pairs
5 local assert = assert
7 local table_concat = table.concat
8 local math_floor, math_modf = math.floor, math.modf
10 module("json.encode.array")
12 function isArray(val, options)
13 local externalIsArray = options and options.array and options.array.isArray
14 local isEncodable = jsonencode.isEncodable
16 if externalIsArray then
17 local ret = externalIsArray(val)
18 if ret == true or ret == false then
19 return ret
20 end
21 end
22 -- Use the 'n' element if it's a number
23 if type(val.n) == 'number' and math_floor(val.n) == val.n and val.n >= 1 then
24 return true
25 end
26 local len = #val
27 for k,v in pairs(val) do
28 if type(k) ~= 'number' then
29 return false
30 end
31 local _, decim = math_modf(k)
32 if not (decim == 0 and 1<=k) then
33 return false
34 end
35 assert(isEncodable(v, options), "Invalid array element type:" .. type(v))
36 if k > len then -- Use Lua's length as absolute determiner
37 return false
38 end
39 end
41 return true
42 end
44 function encode(tab, options)
45 local encodeValue = jsonencode.encodeValue
46 local retVal = {}
47 for i = 1,(tab.n or #tab) do
48 retVal[#retVal + 1] = encodeValue(tab[i], options)
49 end
50 return '[' .. table_concat(retVal, ',') .. ']'
51 end