all: 5.2 compatibility
[luajson.git] / lua / json / encode / others.lua
blobbd199cf3b228686f0ea31dfa8e3d356f48f74ace
1 --[[
2 Licensed according to the included 'LICENSE' document
3 Author: Thomas Harning Jr <harningt@gmail.com>
4 ]]
5 local tostring = tostring
7 local assert = assert
8 local jsonutil = require("json.util")
9 local util_merge = require("json.util").merge
10 local type = type
12 local is_52 = _VERSION == "Lua 5.2"
13 local _G = _G
15 if is_52 then
16 _ENV = nil
17 end
19 -- Shortcut that works
20 local encodeBoolean = tostring
22 local defaultOptions = {
23 allowUndefined = true,
24 null = jsonutil.null,
25 undefined = jsonutil.undefined
28 local default = nil -- Let the buildCapture optimization take place
29 local strict = {
30 allowUndefined = false
33 local function getEncoder(options)
34 options = options and util_merge({}, defaultOptions, options) or defaultOptions
35 local function encodeOthers(value, state)
36 if value == options.null then
37 return 'null'
38 elseif value == options.undefined then
39 assert(options.allowUndefined, "Invalid value: Unsupported 'Undefined' parameter")
40 return 'undefined'
41 else
42 return false
43 end
44 end
45 local function encodeBoolean(value, state)
46 return value and 'true' or 'false'
47 end
48 local nullType = type(options.null)
49 local undefinedType = options.undefined and type(options.undefined)
50 -- Make sure that all of the types handled here are handled
51 local ret = {
52 boolean = encodeBoolean,
53 ['nil'] = function() return 'null' end,
54 [nullType] = encodeOthers
56 if undefinedType then
57 ret[undefinedType] = encodeOthers
58 end
59 return ret
60 end
62 local others = {
63 encodeBoolean = encodeBoolean,
64 default = default,
65 strict = strict,
66 getEncoder = getEncoder
69 if not is_52 then
70 _G.json = _G.json or {}
71 _G.json.encode = _G.json.encode or {}
72 _G.json.encode.others = others
73 end
75 return others