I’m trying to sort a table I’ve populated by numerical order, but for some reason it’s sorting ‘alphapetically’ (if that makes sense.)
For example, a set of five numbers:
7, 10, 13, 2, 3 will sort as 10, 13, 2, 3, 7.
12, 1, 8, 5, 7 will sort as 1, 12, 5, 7, 8
5, 11, 4, 13, 3 will sort as 11, 13, 3, 4, 5
etc. etc… ‘alphabetically’ in that the numbers are being sorted by their first digit across the board, then the second, so that an 11 would indeed come before 3 based on the fact that it ‘started’ with a “1”.
In trying to sort it out, this sample code works just fine for me:
[lua]t = { 2,5,12,10,4 }
table.sort(t)
print(table.concat(t, ", "))[/lua]
whereas a table I just built using a preceeding function does the weird number ordering like the examples above.
I’m pretty sure the table doesn’t have anything unusual in there causing the problem, or at least if I print it out using:
[lua]print(table.concat(numstest, ", ")) [/lua]
The result in the console (as another example) is 13, 8, 13, 4, 5
But when I try to sort that immediately afterwards using the same code:
[lua]table.sort(numstest)
print(table.concat(numstest, ", "))[/lua]
The ‘sorted’ result is 13, 13, 4, 5, 8.
-
I don’t see the difference between the two tables prior to sort that would make them behave differently; as far as I can tell they’re both just tables holding 5 numbers at that point?
-
I’m suppose I’m extra confused because I thought that Lua tables in general didn’t (couldn’t?) have their contents defined by a particular type, so I’m not sure how the same command could possibly treat these two examples differently?
-
Is there in fact a way I should be telling sort that it’s sorting numbers in particular, or specifically defining the table as a numerical array?
I should point out in case it’s relevant, that I had populated this table with sub strings from another table. THAT (original) table had values that contained letters followed by numbers.
For (a bingo) example, the original table records might be
[lua]originalTable = { B46, I57, G39, G71, O2 } [/lua]
From which the numbers only table was populated using something like this:
[lua]for i=1, 5 do
y = string.sub(originalTable[i], 2)
table.insert(numberonlyTable,y)
end [/lua]
it crossed my mind that because the first table contained letters, perhaps the new table was also being considered alphanumeric rather than straight numbers, though again I was under the impression things didn’t work like that
Could anyone point me in the right direction as to why it’s not sorting as intended? [import]uid: 49694 topic_id: 20906 reply_id: 320906[/import]