From c583e8dd2c04bcaeb7496c576b1bc79aca7f8f39 Mon Sep 17 00:00:00 2001 From: Aaron Suen Date: Fri, 27 Mar 2020 22:06:00 -0400 Subject: [PATCH] Beef up lua hook, more extensive JSON support. --- .lualocals | 1 + luahook.lua | 64 ++++++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 54 insertions(+), 11 deletions(-) create mode 100644 .lualocals diff --git a/.lualocals b/.lualocals new file mode 100644 index 0000000..ea96f55 --- /dev/null +++ b/.lualocals @@ -0,0 +1 @@ +print diff --git a/luahook.lua b/luahook.lua index 3dee83e..a7f8dbe 100644 --- a/luahook.lua +++ b/luahook.lua @@ -1,13 +1,55 @@ -local tostring = tostring -local fmt = string.format -local function q(x) return fmt("%q", tostring(x)) end +-- LUALOCALS < --------------------------------------------------------- +local dofile, io, ipairs, pairs, print, rawset, string, table, + tostring, type + = dofile, io, ipairs, pairs, print, rawset, string, table, + tostring, type +local io_open, string_format, table_concat + = io.open, string.format, table.concat +-- LUALOCALS > --------------------------------------------------------- + +local function slurp(fn) + local f = io_open(fn, "rb") + if not f then return end + local x = f:read("*all") + f:close() + return x +end +rawset(_G, "slurp", slurp) + +local ser = {} +local function tojson(x) + return (ser[type(x)])(x) +end +ser["nil"] = function() + return "null" +end +ser["function"] = ser["nil"] +ser["userdata"] = ser["nil"] +ser["thread"] = ser["nil"] +ser["number"] = function(x) + return tostring(x) +end +ser["boolean"] = ser["number"] +ser["string"] = function(x) + return string_format("%q", x) +end +ser["table"] = function(x) + local arr = {} + for k, v in ipairs(x) do + arr[k] = tojson(v) + end + for k, v in pairs(x) do + if arr[k] == nil then + local obj = {} + for k, v in pairs(x) do + obj[#obj + 1] = string_format("%q:%s", tostring(k), arr[k] or tojson(v)) + end + return "{" .. table_concat(obj, ",") .. "}" + end + end + return "[" .. table_concat(arr, ",") .. "]" +end +rawset(_G, "tojson", tojson) local data = dofile("./.cdbrelease.lua") - -print("{") -local comma = "" -for k, v in pairs(data) do - print(comma .. q(k) .. ": " .. q(v)) - comma = "," -end -print("}") +print(tojson(data))