Lua log files: Use shorthand string notation

This commit is contained in:
Lars Mueller 2021-04-22 13:32:38 +02:00
parent 5067cc6981
commit c13beb923b

@ -62,8 +62,7 @@ if minetest then
end) end)
end end
-- TODO use shorthand notations function lua_log_file:_dump(value, is_key)
function lua_log_file:dump(value)
if value == nil then if value == nil then
return "nil" return "nil"
end end
@ -86,25 +85,34 @@ function lua_log_file:dump(value)
end end
self.reference_count = self.reference_count + 1 self.reference_count = self.reference_count + 1
local reference = self.reference_count local reference = self.reference_count
local key = "R[" .. reference .."]"
self.references[value] = reference self.references[value] = reference
local formatted local formatted
if _type == "string" then if _type == "string" then
if is_key and value:len() <= key:len() and value:match"[%a_][%a%d_]*" then
-- Short key
return value, true
end
formatted = ("%q"):format(value) formatted = ("%q"):format(value)
if formatted:len() <= key:len() then
-- Short string
return formatted
end
elseif _type == "table" then elseif _type == "table" then
local entries = {} local entries = {}
for _, value in ipairs(value) do for _, value in ipairs(value) do
table.insert(entries, self:dump(value)) table.insert(entries, self:_dump(value))
end end
for key, value in pairs(value) do for key, value in pairs(value) do
if type(key) ~= "number" or key % 1 ~= 0 or key < 1 or key > #value then if type(key) ~= "number" or key % 1 ~= 0 or key < 1 or key > #value then
table.insert(entries, "[" .. self:dump(key) .. "]=" .. self:dump(value)) local dumped, short = self:_dump(key, true)
table.insert(entries, (short and dumped or ("[" .. dumped .. "]")) .. "=" .. self:_dump(value))
end end
end end
formatted = "{" .. table.concat(entries, ";") .. "}" formatted = "{" .. table.concat(entries, ";") .. "}"
else else
error("unsupported type: " .. _type) error("unsupported type: " .. _type)
end end
local key = "R[" .. reference .."]"
self:log(key .. "=" .. formatted) self:log(key .. "=" .. formatted)
return key return key
end end
@ -114,7 +122,9 @@ function lua_log_file:set(table, key, value)
if not self.references[table] then if not self.references[table] then
error"orphan table" error"orphan table"
end end
self:log(self:dump(table) .. "[" .. self:dump(key) .. "]=" .. self:dump(value)) table = self:_dump(table)
local key, short_key = self:_dump(key, true)
self:log(table .. (short_key and ("." .. key) or ("[" .. key .. "]")) .. "=" .. self:_dump(value))
end end
function lua_log_file:set_root(key, value) function lua_log_file:set_root(key, value)
@ -125,7 +135,7 @@ function lua_log_file:_write()
self.references = {} self.references = {}
self.reference_count = 0 self.reference_count = 0
self:log"R={}" self:log"R={}"
self:dump(self.root) self:_dump(self.root)
end end
function lua_log_file:_rewrite() function lua_log_file:_rewrite()