diff --git a/analyze_structure.lua b/analyze_structure.lua index 07a7f7f..f215869 100644 --- a/analyze_structure.lua +++ b/analyze_structure.lua @@ -211,13 +211,21 @@ end -------------------------------------------------------------------------------- -local function analyze_structure (root, max_depth) - if type(root) ~= 'table' then return {} end - assert(type(root) == 'table') +local function analyze_structure (root, max_depth, info) + -- Argument fixing + local info = info or {} local max_depth = max_depth or math.huge - assert(type(max_depth) == 'number') - local info, visited, next_mark, depth = { root = root }, {}, 1, { [root] = 0 } + -- Quick return + if type(root) ~= 'table' then return info end + + -- Error checking + assert(type(root) == 'table') + + if type(max_depth) ~= 'number' then error(('[pretty/internal]: Bad argument #2, expected number, got %s (%s)'):format(max_depth, type(max_depth)), 2) end + + info.root = info.root or root + local visited, next_mark, depth = {}, 1, { [root] = 0 } local queue = { root, bottom = 1, top = 2 } while queue.bottom < queue.top do diff --git a/test/test_analyze_structure.lua b/test/test_analyze_structure.lua index 95f2ee8..4ac85ff 100644 --- a/test/test_analyze_structure.lua +++ b/test/test_analyze_structure.lua @@ -262,6 +262,21 @@ SUITE:addTest('next_mark does not escape', function () assert(not info.next_mark) end) +SUITE:addTest('We can extend an already existing info table', function () + local tab1, tab2 = {}, {} + local info = analyze_structure( tab1 ) + analyze_structure( tab2, math.huge, info ) + assert(info[tab1]) + assert(info[tab2]) +end) + +SUITE:addTest('When we extend an info table, we retain the previous root', function () + local tab1, tab2 = {}, {} + local info = analyze_structure( tab1 ) + analyze_structure( tab2, math.huge, info ) + assert(tab1 == info.root) +end) + -------------------------------------------------------------------------------- return SUITE