1

So, having some issues getting this table to sort correctly.

Basically, table.sort thinks 10 == 1, 20 == 2, and so on. I'll post my sort code below, but I'm not sure if that has anything to do with it. Is this just an inherent issue with the table.sort algorithm in Lua?

if svKey == "q" and metalMatch == true then
    table.sort(vSort.metals, function(oneMQ, twoMQ)
        return oneMQ.metalQ > twoMQ.metalQ
    end)
end

Values stored in vSort.metals.metalQ are strings anywhere from 1 to 3 digits long. Is there a way to make table.sort differentiate between single-, double-, and triple-digit values?

1
  • 1
    Include a sample of your input and the matching output. table.sort should not be operating the way you say it is. That being said if your sort function doesn't provide the guarantees that lua expects you will get weird results. What happens if you invert your check (twoMQ.metalQ < oneMQ.metalQ)? Commented Jun 3, 2014 at 2:41

1 Answer 1

3

The order operators work as follows. If both arguments are numbers, then they are compared as such. Otherwise, if both arguments are strings, then their values are compared according to the current locale. You can set the locale. Strings are compared lexicographically, which is generally character by character with shorter strings before longer strings.

If you want a numeric sort, then use, well, a numeric type. This might work:

function(oneMQ, twoMQ)
    return tonumber(oneMQ.metalQ) > tonumber(twoMQ.metalQ)
end

It assumes that all the metalQ values are numeric. If not, coerce to a default or provide a fallback sort order in your sort expression for non-numeric values.

Not the answer you're looking for? Browse other questions tagged or ask your own question.