From d848c96fb1af5f226364712f0240019e9ca17a46 Mon Sep 17 00:00:00 2001 From: Jon Michael Aanes Date: Mon, 16 Jan 2017 16:22:46 +0100 Subject: [PATCH] Very minor work on recursion. --- pretty.lua | 8 +++++--- test/test_pretty.lua | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/pretty.lua b/pretty.lua index 32b89be..f2f5fbf 100644 --- a/pretty.lua +++ b/pretty.lua @@ -196,7 +196,7 @@ local function escape_string (str) end local function get_function_info (f) - -- NOTE: Functions best in LuaJIT or Lua 5.2+ + -- NOTE: Works best in LuaJIT or Lua 5.2+ -- Regarding get-info: -- * No need to includ 'f'. Function is already known @@ -454,9 +454,11 @@ function format_table (t, options, depth, l) -- Empty or exteeding max-depth? if table_type == TABLE_TYPE_EMPTY then l[#l+1] = '{}'; return - elseif depth ~= 'max' and depth >= options.max_depth then l[#l+1] = '{...}'; return + elseif depth ~= 'max' and depth >= options.max_depth or l.visited[t] then l[#l+1] = '{...}'; return end + l.visited[t] = true + -- Single line? if is_single_line_table(t) then format_single_line_map(t, options, l); return end @@ -651,7 +653,7 @@ end -------------------------------------------------------------------------------- local function pretty_format (value, options) - local l = {} + local l = { visited = { next_mark = 1 } } local options = options or {} options.max_depth = options.max_depth or math.huge options.indent = options.indent or '\t' diff --git a/test/test_pretty.lua b/test/test_pretty.lua index 6eafb51..31bcde2 100644 --- a/test/test_pretty.lua +++ b/test/test_pretty.lua @@ -650,6 +650,29 @@ format_test { expect = '{\n\t{ a = \'hello\', b = \'hi\' },\n\t{ a = \'hi\', b = \'hello\' }\n}', } +-------------------------------------------------------------------------------- +-- Table recursion + +do + local recursive = {} + recursive[1] = recursive + format_test { + input = recursive, + options = { max_depth = 5 }, + expect = '{ {...} }', + } + format_test { + input = recursive, + options = { max_depth = 5, recursion = 'ignore' }, + expect = '{ {...} }', + } + format_test { + input = recursive, + options = { max_depth = 5, recursion = 'marked' }, + expect = '<1>{ <1>{...} }', + } +end + -------------------------------------------------------------------------------- -- Table Sorting