Skip to content

Commit 823345b

Browse files
committed
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.
1 parent ba06518 commit 823345b

2 files changed

Lines changed: 4 additions & 4 deletions

File tree

compat53/module.lua

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -671,8 +671,8 @@ if lua_version < "5.3" then
671671
["\""] = "\\\""
672672
}
673673

674-
local function addquoted(c)
675-
return addqt[c] or string_format("\\%03d", c:byte())
674+
local function addquoted(c, d)
675+
return (addqt[c] or string_format(d~="" and "\\%03d" or "\\%d", c:byte()))..d
676676
end
677677

678678
function M.string.format(fmt, ...)
@@ -684,7 +684,7 @@ if lua_version < "5.3" then
684684
if kind == "s" then
685685
args[i] = _G.tostring(args[i])
686686
elseif kind == "q" then
687-
args[i] = '"'..string_gsub(args[i], "[%z%c\\\"\n]", addquoted)..'"'
687+
args[i] = '"'..string_gsub(args[i], "([%z%c\\\"\n])(%d?)", addquoted)..'"'
688688
return lead.."%"..mods.."s"
689689
end
690690
end

tests/test.lua

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -505,7 +505,7 @@ do
505505
return _tostring(v)
506506
end
507507
end
508-
print("string.format()", string.format("%q", "\"\\\0000\0010\r0\n0\t0\""))
508+
print("string.format()", string.format("%q", "\"\\\0000\0010\002\r\n0\t0\""))
509509
print("string.format()", string.format("%12.3fx%%sxx%.6s", 3.1, {}))
510510
print("string.format()", string.format("%-3f %%%s %%s", 3.1, true))
511511
print("string.format()", string.format("% 3.2g %%d %%%s", 3.1, nil))

0 commit comments

Comments
 (0)