decoder: Refactored decoding mechanism to permit building even more customized decoders
[luajson.git] / src / json / decode / number.lua
blobdb536404601ba980e5ba34bf96f730cdc5385548
1 --[[
2 Licensed according to the included 'LICENSE' document
3 Author: Thomas Harning Jr <harningt@gmail.com>
4 ]]
5 local lpeg = require("lpeg")
6 local tonumber = tonumber
7 local util = require("json.decode.util")
9 module("json.decode.number")
11 local space = util.space
13 local digit = lpeg.R("09")
14 local digits = digit^1
16 -- Deviation from JSON spec: Leading zeroes, inf number negatives w/ space
17 int = lpeg.P('-')^0 * space^0 * digits
18 local int = int
19 local strictInt = (lpeg.P('-') + 0) * (lpeg.R("19") * digits + digit)
21 local frac = lpeg.P('.') * digits
23 local exp = lpeg.S("Ee") * (lpeg.S("-+") + 0) * digits
25 local nan = lpeg.S("Nn") * lpeg.S("Aa") * lpeg.S("Nn")
26 local inf = lpeg.S("Ii") * lpeg.P("nfinity")
28 local defaultOptions = {
29 nan = true,
30 inf = true,
31 frac = true,
32 exp = true
35 default = {}
36 strict = {
37 nan = false,
38 inf = false,
39 strict = true
41 --[[
42 Options: configuration options for number rules
43 nan: match NaN
44 inf: match Infinity
45 strict: for integer portion, only match [-]([0-9]|[1-9][0-9]*)
46 frac: match fraction portion (.0)
47 exp: match exponent portion (e1)
48 DEFAULT: nan, inf, frac, exp
49 Must be set to false
51 function buildMatch(options)
52 options = util.merge({}, defaultOptions, options)
53 local ret = options.strict and strictInt or int
54 if options.frac then
55 ret = ret * (frac + 0)
56 end
57 if options.exp then
58 ret = ret * (exp + 0)
59 end
60 if options.nan then
61 ret = ret + nan
62 end
63 if options.inf then
64 ret = ret + inf
65 end
66 return ret
67 end
69 function buildCapture(options)
70 return buildMatch(options) / tonumber
71 end