nested tables

This commit is contained in:
Enrique García Cota 2011-04-23 20:17:43 +02:00
parent 77104ea09e
commit b8286f82dc
2 changed files with 42 additions and 20 deletions

View File

@ -7,32 +7,44 @@
-- public function -- public function
local bufferMethods = { local Buffer = {}
add = function(self, ...)
function Buffer:new()
return setmetatable( { data = {} }, {
__index = Buffer,
__tostring = function(instance) return table.concat(instance.data) end
} )
end
function Buffer:add(...)
local args = {...} local args = {...}
for i=1, #args do for i=1, #args do
table.insert(self.data, tostring(args[i])) table.insert(self.data, tostring(args[i]))
end end
return self return self
end end
}
function Buffer:addValue(v)
local tv = type(v)
if tv == 'table' then
self:add('{')
for i=1, #v do
if i > 1 then self:add(', ') end
self:addValue(v[i])
end
self:add('}')
else
self:add(tostring(v))
end
return self
end
local function newBuffer() local function newBuffer()
return setmetatable( { data = {} }, {
__index = bufferMethods,
__tostring = function(self) return table.concat(self.data) end
} )
end end
local function inspect(t) local function inspect(t)
local buffer = newBuffer() return tostring(Buffer:new():addValue(t))
buffer:add('{')
for i=1, #t do
if i > 1 then buffer:add(', ') end
buffer:add(tostring(t[i]))
end
buffer:add('}')
return tostring(buffer)
end end
return inspect return inspect

View File

@ -2,8 +2,18 @@ local inspect = require 'inspect'
context( 'inspect', function() context( 'inspect', function()
test('Should work with numbers', function()
assert_equal(inspect(1), "1")
assert_equal(inspect(1.5), "1.5")
assert_equal(inspect(-3.14), "-3.14")
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)
test('Should work with nested arrays', function()
assert_equal(inspect({1,2,3, {4,5}, 6}), "{1, 2, 3, {4, 5}, 6}" )
end)
end) end)