comparison util/json.lua @ 9329:19bc3ec13f07

util.json: Use util.iterators.sorted_pairs() in ordered mode
author Matthew Wild <mwild1@gmail.com>
date Fri, 21 Sep 2018 14:35:35 +0100
parents c60fdf148118
children 997f3ca90628
comparison
equal deleted inserted replaced
9328:a9592107021b 9329:19bc3ec13f07
5 -- This project is MIT/X11 licensed. Please see the 5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information. 6 -- COPYING file in the source package for more information.
7 -- 7 --
8 8
9 local type = type; 9 local type = type;
10 local t_insert, t_concat, t_remove, t_sort = table.insert, table.concat, table.remove, table.sort; 10 local t_insert, t_concat, t_remove = table.insert, table.concat, table.remove;
11 local s_char = string.char; 11 local s_char = string.char;
12 local tostring, tonumber = tostring, tonumber; 12 local tostring, tonumber = tostring, tonumber;
13 local pairs, ipairs = pairs, ipairs; 13 local pairs, ipairs, spairs = pairs, ipairs, require "util.iterators".sorted_pairs;
14 local next = next; 14 local next = next;
15 local getmetatable, setmetatable = getmetatable, setmetatable; 15 local getmetatable, setmetatable = getmetatable, setmetatable;
16 local print = print; 16 local print = print;
17 17
18 local has_array, array = pcall(require, "util.array"); 18 local has_array, array = pcall(require, "util.array");
93 end 93 end
94 end 94 end
95 if next(__hash) ~= nil or next(hash) ~= nil or next(__array) == nil then 95 if next(__hash) ~= nil or next(hash) ~= nil or next(__array) == nil then
96 t_insert(buffer, "{"); 96 t_insert(buffer, "{");
97 local mark = #buffer; 97 local mark = #buffer;
98 if buffer.ordered then 98 local _pairs = buffer.ordered and spairs or pairs;
99 local keys = {}; 99 for k,v in _pairs(hash) do
100 for k in pairs(hash) do 100 stringsave(k, buffer);
101 t_insert(keys, k); 101 t_insert(buffer, ":");
102 end 102 simplesave(v, buffer);
103 t_sort(keys); 103 t_insert(buffer, ",");
104 for _,k in ipairs(keys) do
105 stringsave(k, buffer);
106 t_insert(buffer, ":");
107 simplesave(hash[k], buffer);
108 t_insert(buffer, ",");
109 end
110 else
111 for k,v in pairs(hash) do
112 stringsave(k, buffer);
113 t_insert(buffer, ":");
114 simplesave(v, buffer);
115 t_insert(buffer, ",");
116 end
117 end 104 end
118 if next(__hash) ~= nil then 105 if next(__hash) ~= nil then
119 t_insert(buffer, "\"__hash\":["); 106 t_insert(buffer, "\"__hash\":[");
120 for k,v in pairs(__hash) do 107 for k,v in pairs(__hash) do
121 simplesave(k, buffer); 108 simplesave(k, buffer);