Skip to content
This repository has been archived by the owner on Jul 26, 2022. It is now read-only.

Commit

Permalink
Compress decimal escapes for string.format("%q").
Browse files Browse the repository at this point in the history
Lua 5.2 escapes 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.
  • Loading branch information
siffiejoe committed Jun 2, 2015
1 parent ad22f7e commit d6e07c8
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
6 changes: 3 additions & 3 deletions compat52.lua
Expand Up @@ -540,8 +540,8 @@ if _VERSION == "Lua 5.1" 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 string.format(fmt, ...)
Expand All @@ -553,7 +553,7 @@ if _VERSION == "Lua 5.1" then
if kind == "s" then
args[i] = _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
Expand Down
2 changes: 1 addition & 1 deletion tests/test.lua
Expand Up @@ -326,7 +326,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))
Expand Down

0 comments on commit d6e07c8

Please sign in to comment.