From b8286f82dcc088a6e12e43c64d6c377aad7e4601 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Garc=C3=ADa=20Cota?= Date: Sat, 23 Apr 2011 20:17:43 +0200 Subject: [PATCH] nested tables --- inspect.lua | 52 ++++++++++++++++++++++++++----------------- spec/inspect_spec.lua | 10 +++++++++ 2 files changed, 42 insertions(+), 20 deletions(-) diff --git a/inspect.lua b/inspect.lua index ccd6a1c..2a81b20 100644 --- a/inspect.lua +++ b/inspect.lua @@ -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])) - end - return self - end -} +local Buffer = {} -local function newBuffer() +function Buffer:new() return setmetatable( { data = {} }, { - __index = bufferMethods, - __tostring = function(self) return table.concat(self.data) end + __index = Buffer, + __tostring = function(instance) return table.concat(instance.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])) +function Buffer:add(...) + local args = {...} + for i=1, #args do + table.insert(self.data, tostring(args[i])) end - buffer:add('}') - return tostring(buffer) + 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 + self:add('}') + else + self:add(tostring(v)) + end + return self +end + +local function newBuffer() + +end + +local function inspect(t) + return tostring(Buffer:new():addValue(t)) end return inspect diff --git a/spec/inspect_spec.lua b/spec/inspect_spec.lua index 8a3a831..7a631e1 100644 --- a/spec/inspect_spec.lua +++ b/spec/inspect_spec.lua @@ -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)