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?
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.
WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 3275 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC