Table (numerical data) sorting 'alphabetically'?

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:

1
2
3
t = { 2,5,12,10,4 }
table.sort(t)
print(table.concat(t, ", "))

If the first example sort works ok, maybe it's you've put quotes round your numbers in your table so it's sorting as a text string rather as numbers?

Else try padding your numbers eg 01, 02 etc.

Lua is typeless, but there are times where things need to be typed.

Try this:

1
table.sort(t, function(a,b) return tonumber(a) < tonumber(b) end)

Thank you kindly both! Forcing a numeric comparison seemed to do the trick. (There was indeed an earlier table from which this one was built with quotes, but it seemed to need them at the time.)

views:1714 update:2012/2/9 11:37:26
corona forums © 2003-2011