diff --git a/README.textile b/README.textile index a8f45f1..65c6ea7 100644 --- a/README.textile +++ b/README.textile @@ -128,11 +128,10 @@ Also, make sure to read the license file; the text of that license file must app h1. Specs -This project uses "telescope":https://github.com/norman/telescope for its specs. If you want to run the specs, you will have to install telescope first. Then just enter the spec folder and execute run.lua: +This project uses "telescope":https://github.com/norman/telescope for its specs. If you want to run the specs, you will have to install telescope first. Then just execute the following from the root inspect folder:
-cd path/to/inspect.lua/specs -lua run.lua +tsc -f spec/*diff --git a/inspect.lua b/inspect.lua index 4e71be9..421f355 100644 --- a/inspect.lua +++ b/inspect.lua @@ -43,7 +43,7 @@ local sortOrdersByType = { ['function'] = 5, ['userdata'] = 6, ['thread'] = 7 } -function sortKeys(a,b) +local function sortKeys(a,b) local ta, tb = type(a), type(b) if ta ~= tb then return sortOrdersByType[ta] < sortOrdersByType[tb] end if ta == 'string' or ta == 'number' then return a < b end @@ -60,6 +60,16 @@ local function getDictionaryKeys(t) return keys end +local function getToStringResultSafely(t, mt) + local __tostring = type(mt) == 'table' and mt.__tostring + local string, status + if type(__tostring) == 'function' then + status, string = pcall(__tostring, t) + string = status and string or 'error: ' .. tostring(string) + end + return string +end + local Inspector = {} function Inspector:new(v, depth) @@ -125,9 +135,8 @@ function Inspector:putTable(t) local length = #t local mt = getmetatable(t) - local __tostring = type(mt) == 'table' and mt.__tostring - local string = type(__tostring) == 'function' and __tostring(t) + local string = getToStringResultSafely(t, mt) if type(string) == 'string' and #string > 0 then self:puts(' -- ', unescape(string)) if length >= 1 then self:tabify() end -- tabify the array values diff --git a/spec/inspect.lua b/spec/inspect.lua deleted file mode 120000 index a5f321a..0000000 --- a/spec/inspect.lua +++ /dev/null @@ -1 +0,0 @@ -../inspect.lua \ No newline at end of file diff --git a/spec/inspect_spec.lua b/spec/inspect_spec.lua index 64fc897..2607b63 100644 --- a/spec/inspect_spec.lua +++ b/spec/inspect_spec.lua @@ -186,6 +186,18 @@ context( 'inspect', function() }]]) end) + test('Should not include an error string if __tostring metamethod throws an error', function() + local foo = { foo = 1, __tostring = function() error('hello', 0) end } + local bar = setmetatable({a = 1}, foo) + assert_equal(inspect(bar), [[<1>{ -- error: hello + a = 1, +