tests: enhances coverage for number parsing options
[luajson.git] / lua / json / encode / others.lua
blobb52704434f6a9e15c79483a8477f201894fae904
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 type = type
11 local _ENV = nil
13 -- Shortcut that works
14 local encodeBoolean = tostring
16 local defaultOptions = {
17 allowUndefined = true,
18 null = jsonutil.null,
19 undefined = jsonutil.undefined
22 local modeOptions = {}
24 modeOptions.strict = {
25 allowUndefined = false
28 local function mergeOptions(options, mode)
29 jsonutil.doOptionMerge(options, false, 'others', defaultOptions, mode and modeOptions[mode])
30 end
31 local function getEncoder(options)
32 options = options and jsonutil.merge({}, defaultOptions, options) or defaultOptions
33 local function encodeOthers(value, state)
34 if value == options.null then
35 return 'null'
36 elseif value == options.undefined then
37 assert(options.allowUndefined, "Invalid value: Unsupported 'Undefined' parameter")
38 return 'undefined'
39 else
40 return false
41 end
42 end
43 local function encodeBoolean(value, state)
44 return value and 'true' or 'false'
45 end
46 local nullType = type(options.null)
47 local undefinedType = options.undefined and type(options.undefined)
48 -- Make sure that all of the types handled here are handled
49 local ret = {
50 boolean = encodeBoolean,
51 ['nil'] = function() return 'null' end,
52 [nullType] = encodeOthers
54 if undefinedType then
55 ret[undefinedType] = encodeOthers
56 end
57 return ret
58 end
60 local others = {
61 encodeBoolean = encodeBoolean,
62 mergeOptions = mergeOptions,
63 getEncoder = getEncoder
66 return others