diff --git a/pretty.lua b/pretty.lua index e5a4ee4..c2a244f 100644 --- a/pretty.lua +++ b/pretty.lua @@ -104,9 +104,8 @@ local VALUE_TYPE_SORT_ORDER = { -------------------------------------------------------------------------------- -- Key-value-pair Util -local function padnum(d) - local dec, n = string.match(d, "(%.?)0*(.+)") - return #dec > 0 and ("%.12f"):format(d) or ("%s%03d%s"):format(dec, #n, n) +local function padnum(minus, dec, zeroes, n) + return dec == '.' and ("%.12f"):format(dec..zeroes..n) or ("%s%03d%s"):format(minus == '' and ':' or minus, #n, n) end local function alphanum_compare_strings (a, b) @@ -115,8 +114,13 @@ local function alphanum_compare_strings (a, b) assert(type(a) == 'string') assert(type(b) == 'string') - local a_padded = a:gsub("%.?%d+", padnum)..("\0%3d"):format(#b) - local b_padded = b:gsub("%.?%d+", padnum)..("\0%3d"):format(#a) + local a_padded = a:gsub("(%-?)(%.?)(0*)(%d+)", padnum)..("\0%3d"):format(#b) + local b_padded = b:gsub("(%-?)(%.?)(0*)(%d+)", padnum)..("\0%3d"):format(#a) + -- Correction for sorting of negative numbers: + if a_padded:sub(1,1) == '-' and b_padded:sub(1,1) == '-' then + a_padded, b_padded = b_padded, a_padded + end + -- local A_padded, B_padded = a_padded:upper(), b_padded:upper() if A_padded == B_padded then return a_padded < b_padded end return A_padded < B_padded diff --git a/test/test_sorting.lua b/test/test_sorting.lua index 1b3a0d2..6292087 100644 --- a/test/test_sorting.lua +++ b/test/test_sorting.lua @@ -87,8 +87,8 @@ format_test { format_test { name = 'Proper sorting of number strings keys', - input = { ['-100'] = 'a', ['-1'] = 'b', ['0'] = 'c', ['1'] = 'd', ['100'] = 'e' }, - expect = '{\n [\'-100\'] = \'b\', [\'-1\'] = \'c\',\n [\'0\'] = \'d\', [\'1\'] = \'e\',\n [\'100\'] = \'f\'\n}', + input = { ['-10'] = 'a', ['-0.5'] = 'b', ['0'] = 'c', ['1'] = 'd', ['10.1'] = 'e' }, + expect = '{\n [\'-10\'] = \'a\', [\'-0.5\'] = \'b\',\n [\'0\'] = \'c\', [\'1\'] = \'d\',\n [\'10.1\'] = \'e\'\n}', }