strings were a bit difficult

This commit is contained in:
Enrique García Cota 2011-04-23 21:00:41 +02:00
parent b8286f82dc
commit 87b3e1d82c
2 changed files with 21 additions and 5 deletions

View File

@ -7,6 +7,16 @@
-- public function -- 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 = {} local Buffer = {}
function Buffer:new() function Buffer:new()
@ -26,7 +36,10 @@ end
function Buffer:addValue(v) function Buffer:addValue(v)
local tv = type(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('{') self:add('{')
for i=1, #v do for i=1, #v do
if i > 1 then self:add(', ') end if i > 1 then self:add(', ') end
@ -39,10 +52,6 @@ function Buffer:addValue(v)
return self return self
end end
local function newBuffer()
end
local function inspect(t) local function inspect(t)
return tostring(Buffer:new():addValue(t)) return tostring(Buffer:new():addValue(t))
end end

View File

@ -8,6 +8,13 @@ context( 'inspect', function()
assert_equal(inspect(-3.14), "-3.14") assert_equal(inspect(-3.14), "-3.14")
end) 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() test('Should work with simple array-like tables', function()
assert_equal(inspect({1,2,3}), "{1, 2, 3}" ) assert_equal(inspect({1,2,3}), "{1, 2, 3}" )
end) end)