Merge pull request #49 from jokajak/bugfix/lpeg_version_check
[luajson.git] / lua / json / encode / output.lua
blob8293b6220625600483d5ae5595343b9a33f472fb
1 --[[
2 Licensed according to the included 'LICENSE' document
3 Author: Thomas Harning Jr <harningt@gmail.com>
4 ]]
5 local type = type
6 local assert, error = assert, error
7 local table_concat = require("table").concat
8 local loadstring = loadstring or load
10 local io = require("io")
12 local setmetatable = setmetatable
14 local output_utility = require("json.encode.output_utility")
16 local _ENV = nil
18 local tableCompositeCache = setmetatable({}, {__mode = 'v'})
20 local TABLE_VALUE_WRITER = [[
21 ret[#ret + 1] = %VALUE%
24 local TABLE_INNER_WRITER = ""
26 --[[
27 nextValues can output a max of two values to throw into the data stream
28 expected to be called until nil is first return value
29 value separator should either be attached to v1 or in innerValue
31 local function defaultTableCompositeWriter(nextValues, beginValue, closeValue, innerValue, composite, encode, state)
32 if type(nextValues) == 'string' then
33 local fun = output_utility.prepareEncoder(defaultTableCompositeWriter, nextValues, innerValue, TABLE_VALUE_WRITER, TABLE_INNER_WRITER)
34 local ret = {}
35 fun(composite, ret, encode, state)
36 return beginValue .. table_concat(ret, innerValue) .. closeValue
37 end
38 end
40 -- no 'simple' as default action is just to return the value
41 local function getDefault()
42 return { composite = defaultTableCompositeWriter }
43 end
45 -- BEGIN IO-WRITER OUTPUT
46 local IO_INNER_WRITER = [[
47 if %WRITE_INNER% then
48 state.__outputFile:write(%INNER_VALUE%)
49 end
51 local IO_VALUE_WRITER = [[
52 state.__outputFile:write(%VALUE%)
55 local function buildIoWriter(output)
56 if not output then -- Default to stdout
57 output = io.output()
58 end
59 local function ioWriter(nextValues, beginValue, closeValue, innerValue, composite, encode, state)
60 -- HOOK OUTPUT STATE
61 state.__outputFile = output
62 if type(nextValues) == 'string' then
63 local fun = output_utility.prepareEncoder(ioWriter, nextValues, innerValue, IO_VALUE_WRITER, IO_INNER_WRITER)
64 local ret = {}
65 output:write(beginValue)
66 fun(composite, ret, encode, state)
67 output:write(closeValue)
68 return nil
69 end
70 end
72 local function ioSimpleWriter(encoded)
73 if encoded then
74 output:write(encoded)
75 end
76 return nil
77 end
78 return { composite = ioWriter, simple = ioSimpleWriter }
79 end
80 local function getIoWriter(output)
81 return function()
82 return buildIoWriter(output)
83 end
84 end
86 local output = {
87 getDefault = getDefault,
88 getIoWriter = getIoWriter
91 return output