From f46ce9b86b76e36edc4626a561fb2080db8526e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Garc=C3=ADa=20Cota?= Date: Sun, 24 Apr 2011 02:09:24 +0200 Subject: [PATCH] added __tostring comment at the beginning, if possible --- inspect.lua | 22 ++++++++++++++++------ spec/inspect_spec.lua | 29 +++++++++++++++++++++++------ 2 files changed, 39 insertions(+), 12 deletions(-) diff --git a/inspect.lua b/inspect.lua index 193e791..794a2bb 100644 --- a/inspect.lua +++ b/inspect.lua @@ -24,7 +24,8 @@ local controlCharsTranslation = { local function unescapeChar(c) return controlCharsTranslation[c] end local function unescape(str) - return string.gsub( str, "(%c)", unescapeChar ) + local result, _ = string.gsub( str, "(%c)", unescapeChar ) + return result end local function isIdentifier(str) @@ -101,10 +102,20 @@ function Inspector:putTable(t) if self.level >= self.depth then self:puts('{...}') else - local length = #t - local comma = false self:puts('{') self:down() + + local length = #t + local mt = getmetatable(t) + local __tostring = type(mt) == 'table' and mt.__tostring + local string = type(__tostring) == 'function' and __tostring(t) + + if type(string) == 'string' and #string > 0 then + self:puts(' -- ', unescape(string)) + if length >= 1 then self:tabify() end -- tabify the array values + end + + local comma = false for i=1, length do comma = self:putComma(comma) self:puts(' '):putValue(t[i]) @@ -117,14 +128,13 @@ function Inspector:putTable(t) self:tabify():putKey(k):puts(' = '):putValue(t[k]) end - local mt = getmetatable(t) - if type(mt) == 'table' then + if mt then comma = self:putComma(comma) self:tabify():puts(' = '):putValue(mt) end self:up() - if #dictKeys > 0 then -- dictionary table. Justify closing } + if #dictKeys > 0 or mt then -- dictionary table. Justify closing } self:tabify() elseif length > 0 then -- array tables have one extra space before closing } self:puts(' ') diff --git a/spec/inspect_spec.lua b/spec/inspect_spec.lua index df414c3..789bfb8 100644 --- a/spec/inspect_spec.lua +++ b/spec/inspect_spec.lua @@ -147,16 +147,33 @@ context( 'inspect', function() end) - test('Should include the metatable as an extra hash attribute', function() - local foo = { foo = 1, __tostring = function(k) return 'foo' end } - local bar = setmetatable({a = 1}, foo) - assert_equal(inspect(bar), [[{ + context('metatables', function() + + test('Should include the metatable as an extra hash attribute', function() + local foo = { foo = 1, __mode = 'v' } + local bar = setmetatable({a = 1}, foo) + assert_equal(inspect(bar), [[{ a = 1, = { - __tostring = - foo = 1, + __mode = "v", + foo = 1 } }]]) + end) + + test('Should include the __tostring metamethod if it exists', function() + local foo = { foo = 1, __tostring = function() return 'hello\nworld' end } + local bar = setmetatable({a = 1}, foo) + assert_equal(inspect(bar), [[{ -- hello\nworld + a = 1, + = { + __tostring = , + foo = 1 + } +}]]) + end) + + end)