diff --git a/inspect.lua b/inspect.lua index d6c159a..71f3b75 100644 --- a/inspect.lua +++ b/inspect.lua @@ -31,9 +31,8 @@ local inspect ={ inspect.KEY = setmetatable({}, {__tostring = function() return 'inspect.KEY' end}) inspect.METATABLE = setmetatable({}, {__tostring = function() return 'inspect.METATABLE' end}) -local rawlen = rawlen or function(t) - return #t -end +-- returns the length of a table, ignoring __len (if it exists) +local rawlen = _G.rawlen or function(t) return #t end -- Apostrophizes the string if it has quotes, but not aphostrophes -- Otherwise, it returns a regular quoted string diff --git a/spec/inspect_spec.lua b/spec/inspect_spec.lua index 4d7ef2a..5f9d46e 100644 --- a/spec/inspect_spec.lua +++ b/spec/inspect_spec.lua @@ -1,6 +1,7 @@ local inspect = require 'inspect' local unindent = require 'spec.unindent' local is_luajit, ffi = pcall(require, 'ffi') +local has_rawlen = type(_G.rawlen) == 'function' describe( 'inspect', function() @@ -74,6 +75,13 @@ describe( 'inspect', function() assert.equals('{ "a", "b", "c", { "d", "e" }, "f" }', inspect({'a','b','c', {'d','e'}, 'f'})) end) + if has_rawlen then + it('handles arrays with a __len metatable correctly (ignoring the __len metatable and using rawlen)', function() + local arr = setmetatable({1,2,3}, {__len = function() return nil end}) + assert.equals("{ 1, 2, 3,\n = {\n __len = \n }\n}", inspect(arr)) + end) + end + it('works with simple dictionary tables', function() assert.equals("{\n a = 1,\n b = 2\n}", inspect({a = 1, b = 2})) end)