user3701402
user3701402

Reputation: 11

Lua table.sort issues

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?

Upvotes: 1

Views: 342

Answers (1)

Tom Blodget
Tom Blodget

Reputation: 20772

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.

Upvotes: 3

Related Questions