all: sets _ENV to nil using local _ENV = nil to avoid global writing
[luajson.git] / lua / json / encode / number.lua
blob290b4404783bab1cfdc698ba800513825c2adc12
1 --[[
2 Licensed according to the included 'LICENSE' document
3 Author: Thomas Harning Jr <harningt@gmail.com>
4 ]]
5 local tostring = tostring
6 local assert = assert
7 local jsonutil = require("json.util")
8 local huge = require("math").huge
10 local _ENV = nil
12 local defaultOptions = {
13 nan = true,
14 inf = true
17 local modeOptions = {}
18 modeOptions.strict = {
19 nan = false,
20 inf = false
23 local function mergeOptions(options, mode)
24 jsonutil.doOptionMerge(options, false, 'number', defaultOptions, mode and modeOptions[mode])
25 end
28 local function encodeNumber(number, options)
29 if number ~= number then
30 assert(options.nan, "Invalid number: NaN not enabled")
31 return "NaN"
32 end
33 if number == huge then
34 assert(options.inf, "Invalid number: Infinity not enabled")
35 return "Infinity"
36 end
37 if number == -huge then
38 assert(options.inf, "Invalid number: Infinity not enabled")
39 return "-Infinity"
40 end
41 return tostring(number)
42 end
44 local function getEncoder(options)
45 options = options and jsonutil.merge({}, defaultOptions, options) or defaultOptions
46 return {
47 number = function(number, state)
48 return encodeNumber(number, options)
49 end
51 end
53 local number = {
54 mergeOptions = mergeOptions,
55 getEncoder = getEncoder
58 return number