From 87b3e1d82ce1282f9134d3b32fd5451e11aff93a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Garc=C3=ADa=20Cota?= Date: Sat, 23 Apr 2011 21:00:41 +0200 Subject: [PATCH] strings were a bit difficult --- inspect.lua | 19 ++++++++++++++----- spec/inspect_spec.lua | 7 +++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/inspect.lua b/inspect.lua index 2a81b20..38004d2 100644 --- a/inspect.lua +++ b/inspect.lua @@ -7,6 +7,16 @@ -- public function +-- Apostrophizes the string if it has quotes, but not aphostrophes +-- Otherwise, it returns regular a requilar quoted string +local function smartQuote(str) + if string.match( string.gsub(str,"[^'\"]",""), '^"+$' ) then + return "'" .. str .. "'" + end + return string.format("%q", str ) +end + + local Buffer = {} function Buffer:new() @@ -26,7 +36,10 @@ end function Buffer:addValue(v) local tv = type(v) - if tv == 'table' then + + if tv == 'string' then + self:add(smartQuote(string.gsub( v, "\n", "\\n" ))) + elseif tv == 'table' then self:add('{') for i=1, #v do if i > 1 then self:add(', ') end @@ -39,10 +52,6 @@ function Buffer:addValue(v) return self end -local function newBuffer() - -end - local function inspect(t) return tostring(Buffer:new():addValue(t)) end diff --git a/spec/inspect_spec.lua b/spec/inspect_spec.lua index 7a631e1..6a45179 100644 --- a/spec/inspect_spec.lua +++ b/spec/inspect_spec.lua @@ -8,6 +8,13 @@ context( 'inspect', function() assert_equal(inspect(-3.14), "-3.14") end) + test('Should work with strings', function() + assert_equal(inspect("hello"), '"hello"') + assert_equal(inspect('I have "quotes"'), "'I have \"quotes\"'") + assert_equal(inspect("I have \"quotes\" and 'apostrophes'"), '"I have \\"quotes\\" and \'apostrophes\'"') + assert_equal(inspect('I have \n new \n lines'), '"I have \\\\n new \\\\n lines"') + end) + test('Should work with simple array-like tables', function() assert_equal(inspect({1,2,3}), "{1, 2, 3}" ) end)