From fe9ab028ce5d2695a27b1305ab4806266bebb580 Mon Sep 17 00:00:00 2001 From: Jon Michael Aanes Date: Mon, 12 Mar 2018 11:58:13 +0100 Subject: [PATCH] Minor improvements when talking about the type of a value. --- assert-gooder.lua | 31 +++++++++++++++++++++++++++++++ test/test_assert-gooder.lua | 2 +- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/assert-gooder.lua b/assert-gooder.lua index 8af2c3d..c6daa4e 100644 --- a/assert-gooder.lua +++ b/assert-gooder.lua @@ -280,11 +280,42 @@ local COMPLEX_TYPES = { ['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) + -- Primitive values ARE their type, and don't need the annotation. 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. if COMPLEX_TYPES[type(val)] then return tostring(val) end + -- Numbers and string should have their types with them. return type(val) .. ' ' .. fmt_val(val) end diff --git a/test/test_assert-gooder.lua b/test/test_assert-gooder.lua index eb5ba4d..a5b7f10 100644 --- a/test/test_assert-gooder.lua +++ b/test/test_assert-gooder.lua @@ -284,7 +284,7 @@ SUITE:addTest('Identify integer', function () local a = 5.21 assert(a % 1 == 0) 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) SUITE:addTest('Identify even number', function ()