Skip to content

Commit

Permalink
nested tables
Browse files Browse the repository at this point in the history
  • Loading branch information
kikito committed Apr 23, 2011
1 parent 77104ea commit b8286f8
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 19 deletions.
50 changes: 31 additions & 19 deletions inspect.lua
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,44 @@

-- public function

local bufferMethods = {
add = function(self, ...)
local args = {...}
for i=1, #args do
table.insert(self.data, tostring(args[i]))
local Buffer = {}

function Buffer:new()
return setmetatable( { data = {} }, {
__index = Buffer,
__tostring = function(instance) return table.concat(instance.data) end
} )
end

function Buffer:add(...)
local args = {...}
for i=1, #args do
table.insert(self.data, tostring(args[i]))
end
return self
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
return self
self:add('}')
else
self:add(tostring(v))
end
}
return self
end

local function newBuffer()
return setmetatable( { data = {} }, {
__index = bufferMethods,
__tostring = function(self) return table.concat(self.data) end
} )

end

local function inspect(t)
local buffer = newBuffer()
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)
return tostring(Buffer:new():addValue(t))
end

return inspect
Expand Down
10 changes: 10 additions & 0 deletions spec/inspect_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,18 @@ local inspect = require 'inspect'

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()
assert_equal(inspect({1,2,3}), "{1, 2, 3}" )
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)

0 comments on commit b8286f8

Please sign in to comment.