This gets into the intricacies of lexicographic string sorting! The reason this is happening is because the keys are strings and not numbers, so they sort per-character, with the first character having the heaviest weight, and so forth. So even though you’re using numbers, they are converted to strings and sorted as strings.
For instance, “aaa” comes before “aba” because “b” is greater than “a”.
For numbers, think about these: “35” and “36”. The “35” comes first because the “5” character (not number) comes before “6”.
Now think about: “315” and “32”: In the first index, each string has a “3” so they are equal. Then we move to the second index, which has a “1” and a “2”. The “1” is less, and so it is considered “less than” the other string, thus “315” comes before “32”.
To fix this, you need to pad your numbers with 0s. For instance, 00315 and 00032, where the 00032 will now come before the 00315. To do this in Lua, all you have to do is use the “%.xi” format, where the “x” is the number of padded 0s. For example:
local n1 = 315
local n2 = 32
n1 = ("%.5i"):format(n1)
n2 = ("%.5i"):format(n2)
print(n1, n2) --> 00315, 00032
local numbers = {n1, n2}
table.sort(numbers)
print(table.concat(numbers, ", ")) --> 00032, 00315
You can read more about it in this StackOverflow thread.
This behavior (and the need for padding numbers) is also noted in the Memory Store documentation: