From cd57345c054659f27e7b9fdf91d30074a6dca997 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=80=E8=90=8C=E5=B0=8F=E6=B1=90?= Date: Thu, 6 Dec 2018 10:21:49 +0800 Subject: =?UTF-8?q?json=E8=A1=A8=E6=94=AF=E6=8C=81null?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/src/json/init.lua | 1 + server/src/json/table.lua | 62 +++++++++++++++++++++++++++++++++++++++++++++++ server/src/service.lua | 23 +++--------------- 3 files changed, 67 insertions(+), 19 deletions(-) create mode 100644 server/src/json/table.lua (limited to 'server/src') diff --git a/server/src/json/init.lua b/server/src/json/init.lua index c28e7aed..db513678 100644 --- a/server/src/json/init.lua +++ b/server/src/json/init.lua @@ -1,6 +1,7 @@ local api = { decode = require 'json.decode', encode = require 'json.encode', + table = require 'json.table', } return api diff --git a/server/src/json/table.lua b/server/src/json/table.lua new file mode 100644 index 00000000..351bfe07 --- /dev/null +++ b/server/src/json/table.lua @@ -0,0 +1,62 @@ + +local pairs = pairs +local next = next +local sort = table.sort +local type = type +local rawset = rawset +local move = table.move +local setmetatable = setmetatable + +local function sort_table(tbl) + if not tbl then + tbl = {} + end + local mt = {} + local keys = {} + local mark = {} + local n = 0 + for key in next, tbl do + n=n+1;keys[n] = key + mark[key] = true + end + sort(keys) + function mt:__newindex(key, value) + rawset(self, key, value) + n=n+1;keys[n] = key + mark[key] = true + if type(value) == 'table' then + sort_table(value) + end + end + function mt:__pairs() + local list = {} + local m = 0 + for key in next, self do + if not mark[key] then + m=m+1;list[m] = key + end + end + if m > 0 then + move(keys, 1, n, m+1) + sort(list) + for i = 1, m do + local key = list[i] + keys[i] = key + mark[key] = true + end + n = n + m + end + local i = 0 + return function () + i = i + 1 + local key = keys[i] + return key, self[key] + end + end + + return setmetatable(tbl, mt) +end + +return function (tbl) + return sort_table(tbl) +end diff --git a/server/src/service.lua b/server/src/service.lua index ae1d8c9d..c5987150 100644 --- a/server/src/service.lua +++ b/server/src/service.lua @@ -64,25 +64,10 @@ function mt:_doProto(proto) local method = proto.method local params = proto.params local response, err = self:_callMethod(method, params) - if id then - if response then - self:_send { - id = id, - result = response, - } - else - self:_send { - id = id, - error = { - code = ErrorCodes.UnknownErrorCode, - message = err or ('Lack of response: ' .. method), - }, - } - end - end - if response == nil then - log.error(err or ('Lack of response: ' .. method)) - end + local proto = json.table() + proto.id = id + proto.result = response + self:_send(proto) end function mt:_buildTextCache() -- cgit v1.2.3