diff --git a/pretty.lua b/pretty.lua index 189b928..eb67fa8 100644 --- a/pretty.lua +++ b/pretty.lua @@ -353,12 +353,10 @@ function format_table (t, options, depth, l) if table_info.type == TABLE_TYPE.EMPTY then -- Empty Map - l[#l+1] = '{}' - return; + return l '{}' elseif depth >= options.max_depth or already_visited then -- Already visited or above max depth - l[#l+1] = '{...}' - return; + return l '{...}' end -- Get key-value pairs, and possibly fill holes. @@ -475,6 +473,17 @@ function format_value (value, _, depth, l) end -------------------------------------------------------------------------------- +-- StringBuilder + +local StringBuilder = {} + StringBuilder.__index = StringBuilder + StringBuilder.__call = function (l, s) l[#l+1] = s end +setmetatable(StringBuilder, { + __call = function() return setmetatable({}, StringBuilder) end +}) + +-------------------------------------------------------------------------------- + local DEBUG_OPTIONS = { _all_function_info = true } @@ -491,6 +500,7 @@ local KNOWN_OPTIONS = { } local function ensure_that_all_options_are_known (options) + assert(type(options) == 'table') for option_name, option_value in pairs(options) do if not KNOWN_OPTIONS[option_name] then error(('[pretty]: Unknown option: %s. Was given value %s (%s)'):format(option_name, option_value, type(option_value)), 2) @@ -501,12 +511,19 @@ local function ensure_that_all_options_are_known (options) end local function pretty_format (value, options) - local l = { visited = { next_mark = 1 } } - l.options = options or {} - l.options.max_depth = l.options.max_depth or math.huge - l.options.indent = l.options.indent or '\t' - ensure_that_all_options_are_known(l.options) - l.info = (type(value) == 'table') and analyze_structure(value) or {} + -- Error checking + options = options or {} + options.max_depth = options.max_depth or math.huge + options.indent = options.indent or '\t' + ensure_that_all_options_are_known(options) + + -- Setup StringBuilder + local l = StringBuilder() + l.visited = { next_mark = 1 } + l.options = options + l.info = (type(value) == 'table') and analyze_structure(value) or {} + + -- Format value. format_value(value, nil, 0, l) -- If any alignment info still exists, ignore it