From 257dbdf06feb366f9eb1f96ceb7026c9365dddaa Mon Sep 17 00:00:00 2001 From: Ricardo Constantino Date: Tue, 15 Aug 2017 17:51:50 +0100 Subject: TOOLS/autoload.lua: implement natural sorting --- TOOLS/lua/autoload.lua | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-) (limited to 'TOOLS/lua') diff --git a/TOOLS/lua/autoload.lua b/TOOLS/lua/autoload.lua index 2ca3b911c1..8802c5d031 100644 --- a/TOOLS/lua/autoload.lua +++ b/TOOLS/lua/autoload.lua @@ -53,6 +53,37 @@ table.filter = function(t, iter) end end +-- splitbynum and alnumcomp from alphanum.lua (C) Andre Bogus +-- Released under the MIT License +-- http://www.davekoelle.com/files/alphanum.lua + +-- split a string into a table of number and string values +function splitbynum(s) + local result = {} + for x, y in (s or ""):gmatch("(%d*)(%D*)") do + if x ~= "" then table.insert(result, tonumber(x)) end + if y ~= "" then table.insert(result, y) end + end + return result +end + +function clean_key(k) + k = (' '..k..' '):gsub("%s+", " "):sub(2, -2):lower() + return splitbynum(k) +end + +-- compare two strings +function alnumcomp(x, y) + local xt, yt = clean_key(x), clean_key(y) + for i = 1, math.min(#xt, #yt) do + local xe, ye = xt[i], yt[i] + if type(xe) == "string" then ye = tostring(ye) + elseif type(ye) == "string" then xe = tostring(xe) end + if xe ~= ye then return xe < ye end + end + return #xt < #yt +end + function find_and_add_entries() local path = mp.get_property("path", "") local dir, filename = mputils.split_path(path) @@ -81,15 +112,7 @@ function find_and_add_entries() end return EXTENSIONS[string.lower(ext)] end) - table.sort(files, function (a, b) - local len = string.len(a) - string.len(b) - if len ~= 0 then -- case for ordering filename ending with such as X.Y.Z - local ext = string.len(get_extension(a)) + 1 - a = string.sub(a, 1, -ext) - b = string.sub(b, 1, -ext) - end - return string.lower(a) < string.lower(b) - end) + table.sort(files, alnumcomp) if dir == "." then dir = "" -- cgit v1.2.3