简体   繁体   English

Lua table.sort问题

[英]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. 基本上, table.sort认为10 == table.sort == 2,依此类推。 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? 这只是Lua中table.sort算法的固有问题吗?

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. 存储在vSort.metals.metalQ中的值是vSort.metals.metalQ为1到3位的字符串。 Is there a way to make table.sort differentiate between single-, double-, and triple-digit values? 有没有办法让table.sort区分单位,双位和三位数值?

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. 它假定所有metalQ值都是数字。 If not, coerce to a default or provide a fallback sort order in your sort expression for non-numeric values. 如果不是,则强制使用默认值或在排序表达式中为非数字值提供回退排序顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM