From 2a5205e53cb2b615ce41e09d308324bd12e78d66 Mon Sep 17 00:00:00 2001 From: Andreas Hofer Date: Tue, 29 Mar 2016 21:58:17 +0200 Subject: [PATCH] fix problem with escaping zero and other control characters --- inspect.lua | 11 ++++++++--- spec/inspect_spec.lua | 5 +++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/inspect.lua b/inspect.lua index 39f43af..a053da6 100644 --- a/inspect.lua +++ b/inspect.lua @@ -41,12 +41,17 @@ local function smartQuote(str) end local controlCharsTranslation = { - ["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", - ["\r"] = "\\r", ["\t"] = "\\t", ["\v"] = "\\v" + ["\\7"] = "\\a", ["\\007"] = "\\a", + ["\\8"] = "\\b", ["\\008"] = "\\b", + ["\\12"] = "\\f", ["\\012"] = "\\f", + ["\\13"] = "\\r", ["\\013"] = "\\r", + ["\\9"] = "\\t", ["\\009"] = "\\t", + ["\\11"] = "\\v", ["\\011"] = "\\v", } local function escape(str) - local result = str:gsub("\\", "\\\\"):gsub("(%c)", controlCharsTranslation) + local f = string.format("%q", str) + local result = f:gsub("\\%d%d?%d?", controlCharsTranslation):gsub("\\\n", "\\n"):gsub('\\"', '"'):sub(2,-2) return result end diff --git a/spec/inspect_spec.lua b/spec/inspect_spec.lua index 9a81642..9264033 100644 --- a/spec/inspect_spec.lua +++ b/spec/inspect_spec.lua @@ -38,6 +38,11 @@ describe( 'inspect', function() assert.equals('"I have \\b a back space"', inspect('I have \b a back space')) end) + it('escapes zeroes and other control characters properly', function() + assert.equals('"I have \\0 zeroes \\0000 and other \\1 control \\0010 characters"', + inspect('I have \0 zeroes \0000 and other \1 control \0010 characters')) + end) + it('backslashes its backslashes', function() assert.equals('"I have \\\\ a backslash"', inspect('I have \\ a backslash')) assert.equals('"I have \\\\\\\\ two backslashes"', inspect('I have \\\\ two backslashes'))