From 823345b8b4de9e2a646dbcd471e05a1c7598d378 Mon Sep 17 00:00:00 2001 From: Philipp Janda Date: Tue, 2 Jun 2015 15:14:31 +0200 Subject: Compress decimal escapes for string.format("%q"). Lua 5.2+ escape all control characters using decimal escape sequences. The previous code did the same but always used three decimals (possibly zero-padded) no matter the following character. The new version only uses all three decimals when another decimal character is following. --- compat53/module.lua | 6 +++--- tests/test.lua | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/compat53/module.lua b/compat53/module.lua index f278f13..56c9932 100644 --- a/compat53/module.lua +++ b/compat53/module.lua @@ -671,8 +671,8 @@ if lua_version < "5.3" then ["\""] = "\\\"" } - local function addquoted(c) - return addqt[c] or string_format("\\%03d", c:byte()) + local function addquoted(c, d) + return (addqt[c] or string_format(d~="" and "\\%03d" or "\\%d", c:byte()))..d end function M.string.format(fmt, ...) @@ -684,7 +684,7 @@ if lua_version < "5.3" then if kind == "s" then args[i] = _G.tostring(args[i]) elseif kind == "q" then - args[i] = '"'..string_gsub(args[i], "[%z%c\\\"\n]", addquoted)..'"' + args[i] = '"'..string_gsub(args[i], "([%z%c\\\"\n])(%d?)", addquoted)..'"' return lead.."%"..mods.."s" end end diff --git a/tests/test.lua b/tests/test.lua index f8fa894..9ac27d4 100755 --- a/tests/test.lua +++ b/tests/test.lua @@ -505,7 +505,7 @@ do return _tostring(v) end end - print("string.format()", string.format("%q", "\"\\\0000\0010\r0\n0\t0\"")) + print("string.format()", string.format("%q", "\"\\\0000\0010\002\r\n0\t0\"")) print("string.format()", string.format("%12.3fx%%sxx%.6s", 3.1, {})) print("string.format()", string.format("%-3f %%%s %%s", 3.1, true)) print("string.format()", string.format("% 3.2g %%d %%%s", 3.1, nil)) -- cgit v1.2.3-55-g6feb