all: 5.2 compatibility
[luajson.git] / lua / json / util.lua
blob8664e9d8889f5406eb28f2c80c8b28625a741513
1 --[[
2 Licensed according to the included 'LICENSE' document
3 Author: Thomas Harning Jr <harningt@gmail.com>
4 ]]
5 local type = type
6 local print = print
7 local tostring = tostring
8 local pairs = pairs
9 local getmetatable, setmetatable = getmetatable, setmetatable
10 local select = select
12 local is_52 = _VERSION == "Lua 5.2"
13 local _G = _G
15 if is_52 then
16 _ENV = nil
17 end
19 local function foreach(tab, func)
20 for k, v in pairs(tab) do
21 func(k,v)
22 end
23 end
24 local function printValue(tab, name)
25 local parsed = {}
26 local function doPrint(key, value, space)
27 space = space or ''
28 if type(value) == 'table' then
29 if parsed[value] then
30 print(space .. key .. '= <' .. parsed[value] .. '>')
31 else
32 parsed[value] = key
33 print(space .. key .. '= {')
34 space = space .. ' '
35 foreach(value, function(key, value) doPrint(key, value, space) end)
36 end
37 else
38 if type(value) == 'string' then
39 value = '[[' .. tostring(value) .. ']]'
40 end
41 print(space .. key .. '=' .. tostring(value))
42 end
43 end
44 doPrint(name, tab)
45 end
47 local function clone(t)
48 local ret = {}
49 for k,v in pairs(t) do
50 ret[k] = v
51 end
52 return ret
53 end
55 local function merge(t, from, ...)
56 if not from then
57 return t
58 end
59 for k,v in pairs(from) do
60 t[k] = v
61 end
62 return merge(t, ...)
63 end
65 -- Function to insert nulls into the JSON stream
66 local function null()
67 return null
68 end
70 -- Marker for 'undefined' values
71 local function undefined()
72 return undefined
73 end
75 local ArrayMT = {}
77 --[[
78 Return's true if the metatable marks it as an array..
79 Or false if it has no array component at all
80 Otherwise nil to get the normal detection component working
82 local function IsArray(value)
83 if type(value) ~= 'table' then return false end
84 local ret = getmetatable(value) == ArrayMT
85 if not ret then
86 if #value == 0 then return false end
87 else
88 return ret
89 end
90 end
91 local function InitArray(array)
92 setmetatable(array, ArrayMT)
93 return array
94 end
96 local CallMT = {}
98 local function isCall(value)
99 return CallMT == getmetatable(value)
102 local function buildCall(name, ...)
103 local callData = {
104 name = name,
105 parameters = {n = select('#', ...), ...}
107 return setmetatable(callData, CallMT)
110 local function decodeCall(callData)
111 if not isCall(callData) then return nil end
112 return callData.name, callData.parameters
115 local json_util = {
116 printValue = printValue,
117 clone = clone,
118 merge = merge,
119 null = null,
120 undefined = undefined,
121 IsArray = IsArray,
122 InitArray = InitArray,
123 isCall = isCall,
124 buildCall = buildCall,
125 decodeCall = decodeCall
128 if not is_52 then
129 _G.json = _G.json or {}
130 _G.json.util = json_util
133 return json_util