util.format: Serialize values for the %q format
authorKim Alvefur <zash@zash.se>
Fri, 12 Oct 2018 01:29:34 +0200
changeset 9697 6ed0d6224d64
parent 9696 affcbccc1dff
child 9698 faebfd3ad2a1
util.format: Serialize values for the %q format Improves eg debug logs
spec/util_format_spec.lua
util/format.lua
--- a/spec/util_format_spec.lua	Sat Dec 08 17:10:51 2018 +0100
+++ b/spec/util_format_spec.lua	Fri Oct 12 01:29:34 2018 +0200
@@ -11,6 +11,7 @@
 			assert.equal("true", format("%s", true));
 			assert.equal("[true]", format("%d", true));
 			assert.equal("% [true]", format("%%", true));
+			assert.equal("{ }", format("%q", { }));
 		end);
 	end);
 end);
--- a/util/format.lua	Sat Dec 08 17:10:51 2018 +0100
+++ b/util/format.lua	Fri Oct 12 01:29:34 2018 +0200
@@ -6,6 +6,7 @@
 local unpack = table.unpack or unpack; -- luacheck: ignore 113/unpack
 local pack = require "util.table".pack; -- TODO table.pack in 5.2+
 local type = type;
+local dump = require "util.serialization".new("debug");
 
 local function format(formatstring, ...)
 	local args = pack(...);
@@ -34,7 +35,10 @@
 			if arg == nil then
 				args[i] = "nil";
 				spec = "<%s>";
-			elseif option == "q" or option == "s" then -- arg should be string
+			elseif option == "q" then
+				args[i] = dump(arg);
+				spec = "%s";
+			elseif option == "s" then
 				args[i] = tostring(arg);
 			elseif type(arg) ~= "number" then -- arg isn't number as expected?
 				args[i] = tostring(arg);