Sorting – Lua: Custom comparison function in table sort

I have a table that stores file names, for example:

1.jpg
5.jpg< br />4.jpg
10.jpg
2.jpg

Now I want to sort it. I used the following code:
table.sort(myTable )

The result is

1.jpg
10.jpg
2.jpg
4.jpg
5.jpg

However, I want to sort like this:

1.jpg
2.jpg
4.jpg
5.jpg
10.jpg

So I wrote a custom comparison function:

function compare(a, b)
return tonumber(a) end

But it appeared: try to compare two zero values. So how can I achieve it?

You need to extract a number from the file name that is compared first. Assuming the number is unique, Something like this should work:

function compare(a, b)
return tonumber(a:match("%d+")) end

You may also want to check out the post on Alphanum sorting for humans in Lua, which covers this case and others.

[Update to solve problems in comments] To sort by a combination of strings and numbers, you only need to follow one option in the linked blog post. For example, to sort the file names listed in the comments, you can Use the following command:

local t = {"file001_abc_10.txt", "file001_abc_2.txt", "file001_bcd_4.txt", "file001_bcd_12.txt"}
function compare(a, b)
local function padnum(n, rest) return ("%03d"..rest):format(tonumber(n)) end
return tostring(a):gsub( "(%d+)(%.)",padnum) end
table.sort(t, compare )
print(unpack(t))

Print: file001_abc_2.txt file001_abc_10.txt file001_bcd_4.txt file001_bcd_12.txt. You can adjust the number length in the padnum function.

div>

I have a table storing file names, for example:

1.jpg
5.jpg
4.jpg
10.jpg
2.jpg

Now I want to sort it. I used the following code:
table.sort(myTable)

The result is

1.jpg
10.jpg< br />2.jpg
4.jpg
5.jpg

However, I want to sort like this:

1. jpg
2.jpg
4.jpg
5.jpg
10.jpg

So I wrote a custom comparison function:

function compare(a, b)
return tonumber(a) end

But it appeared: try to compare Two zero values. So how can I achieve it?

You need to extract a number from the file name that is compared first. Assuming the number is unique, something like this should work:

function compare(a, b)
return tonumber(a:match("%d+")) end

You may also want to check out the post on Alphanum sorting for humans in Lua, which covers this case and other cases.

[Update to solve the problem in the comments] To sort by a combination of string and number, you only need to follow an option in the linked blog post. For example, to sort the file names listed in the comments, you can use the following command:

< /p>

local t = {"file001_abc_10.txt", "file001_abc_2.txt", "file001_bcd_4.txt", "file001_bcd_12.txt"}
function compare(a, b)
local function padnum(n, rest) return ("%03d"..rest):format(tonumber(n)) end
return tostring(a):gsub("(%d+)(%.)",padnum ) end
table.sort(t, compare)
print(unpack(t))

Print: file001_abc_2.txt file001_abc_10.txt file001_bcd_4.txt file001_bcd_12.txt. You can adjust the number length in the padnum function.

Leave a Comment

Your email address will not be published.