Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve output of userdata, handling__tostring and NULL #45

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions inspect.lua
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,19 @@ local function getNonSequentialKeys(t)
return keys, keysLength, sequenceLength
end

local function getToStringResultSafely(t, mt)
if type(t) ~= "userdata" then
return
end
local __tostring = type(mt) == 'table' and rawget(mt, '__tostring')
local str, ok
if type(__tostring) == 'function' then
ok, str = pcall(__tostring, t)
str = ok and str or 'error: ' .. tostring(str)
end
if type(str) == 'string' and #str > 0 then return str end
end

local function countTableAppearances(t, tableAppearances)
tableAppearances = tableAppearances or {}

Expand Down Expand Up @@ -293,6 +306,20 @@ function Inspector:putValue(v)
self:puts(tostring(v))
elseif tv == 'table' then
self:putTable(v)
elseif tv == 'userdata' then
local mt = getmetatable(v)
local toStringResult = mt and getToStringResultSafely(v, mt)
if toStringResult then
self:puts('<userdata ', self:getId(v), '>')
self:puts(' -- ', escape(toStringResult))
else
local str = tostring(v)
if str == "userdata: NULL" then
self:puts('<userdata NULL>')
else
self:puts('<userdata ', self:getId(v), '>')
end
end
else
self:puts('<', tv, ' ', self:getId(v), '>')
end
Expand Down
11 changes: 11 additions & 0 deletions spec/inspect_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,17 @@ describe( 'inspect', function()
]]), inspect(bar))
end)

it('includes the __tostring metamethod of userdata', function()
local tbl = {
f = io.tmpfile(),
}
assert.equals(unindent([[
{
f = <userdata 1> -- $FILE
}
]]):gsub("$FILE", tostring(tbl.f)), inspect(tbl))
end)

it('can be used on the __tostring metamethod of a table without errors', function()
local f = function(x) return inspect(x) end
local tbl = setmetatable({ x = 1 }, { __tostring = f })
Expand Down