1
0

Minor improvements when talking about the type of a value.

This commit is contained in:
Jon Michael Aanes 2018-03-12 11:58:13 +01:00
parent d9be06658d
commit fe9ab028ce
2 changed files with 32 additions and 1 deletions

View File

@ -280,11 +280,42 @@ local COMPLEX_TYPES = {
['function'] = true, ['function'] = true,
} }
local function fmt_table_with_type (val)
assert(type(val) == 'table')
local subtype = 'table'
-- Find "last key"
do
local last_key, num_visited = nil, 0
repeat last_key, num_visited = next(val, last_key), num_visited + 1
until last_key == nil or type(last_key) ~= 'number' or last_key <= 0 or last_key > #val
-- Conclude:
if last_key == nil then
subtype = (num_visited == 1) and 'empty table' or 'sequence'
end
end
local addr = tostring(val):match '^table: (.*)$'
local attr = debug.getmetatable(val) ~= nil and ' with metatable' or ''
return ('%s%s: %s'):format(subtype, attr, addr)
end
local function fmt_val_with_type (val) local function fmt_val_with_type (val)
-- Primitive values ARE their type, and don't need the annotation. -- Primitive values ARE their type, and don't need the annotation.
if PRIMITIVE_VALUES[type(val)] then return tostring(val) end if PRIMITIVE_VALUES[type(val)] then return tostring(val) end
-- Tables can be of many different styles
if type(val) == 'table' then
return fmt_table_with_type(val)
end
-- Complex types are already formatted with some type information. -- Complex types are already formatted with some type information.
if COMPLEX_TYPES[type(val)] then return tostring(val) end if COMPLEX_TYPES[type(val)] then return tostring(val) end
-- Numbers and string should have their types with them. -- Numbers and string should have their types with them.
return type(val) .. ' ' .. fmt_val(val) return type(val) .. ' ' .. fmt_val(val)
end end

View File

@ -284,7 +284,7 @@ SUITE:addTest('Identify integer', function ()
local a = 5.21 local a = 5.21
assert(a % 1 == 0) assert(a % 1 == 0)
end) end)
assert_equal('./test/test_assert-gooder.lua:'..curline(-2)..': '..'assertion failed! bad local \'a\' (integer expected, but got floating-point number 5.21)', msg) assert_equal('./test/test_assert-gooder.lua:'..curline(-2)..': '..'assertion failed! bad local \'a\' (integer expected, but got decimal number 5.21)', msg)
end) end)
SUITE:addTest('Identify even number', function () SUITE:addTest('Identify even number', function ()