all: 5.2 compatibility
[luajson.git] / lua / json / encode / number.lua
blob63a5786e7300e59520dbdb5872db4cd519b7e40d
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 util = require("json.util")
8 local huge = require("math").huge
10 local is_52 = _VERSION == "Lua 5.2"
11 local _G = _G
13 if is_52 then
14 _ENV = nil
15 end
17 local defaultOptions = {
18 nan = true,
19 inf = true
22 local default = nil -- Let the buildCapture optimization take place
23 local strict = {
24 nan = false,
25 inf = false
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 util.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 default = default,
55 strict = strict,
56 getEncoder = getEncoder
59 if not is_52 then
60 _G.json = _G.json or {}
61 _G.json.encode = _G.json.encode or {}
62 _G.json.encode.number = number
63 end
65 return number