首页 > 解决方案 > 为什么 Lua 的 table.sort 方法对我的数据不起作用

问题描述

我正在尝试对数组类型的数据表进行看似非常简单的排序过程。

这是我的排序功能:

function ArraySort(t)
    local sorted = {}
    for i in ipairs(t) do table.insert(sorted,t[i]) end
    table.sort(sorted)
    return sorted
end

以下是原始数据的样子:

T:------[presets unsorted]-----
1 = Showdown
2 = Kora
3 = Marxophone
4 = Mountain Home
5 = Soft Koto
6 = ElectroClav
7 = Bad Actor
8 = Glass Harp
9 = Panorama
10 = Winwood
11 = ElectroTuba
12 = alto flute
13 = Clear Bell
14 = Third Man
15 = Wooden Bars
16 = Silver Bowl
17 = Rayong
18 = frippery
19 = red cedar
20 = theater flutes
21 = lowrey
22 = theater flutes 2
23 = Steel String
24 = quiet place 
25 = treadwell pad
26 = alpen drive
27 = Bassonery
28 = Clarinets
29 = Silent Movie
30 = Hudi-gurdi
31 = Silent Screen
32 = Light Bulb
33 = Zithar Pad
34 = Oboid Jazz
35 = Quacking
36 = More Quacking
37 = Horn Ensemble
38 = Knell
39 = steampipe
40 = Saturated Ping
41 = fuzz floot
42 = Thin Pad
43 = SheenPad
44 = flutar
45 = Acoustic Bass
46 = new whirled
47 = heavy breathing
48 = whisper cycle
49 = 2nd Harmonium
50 = Tubular Bells
51 = Fat Clav
52 = Obese Clav
53 = clank
54 = ghost flute
55 = alto flute
56 = ghost Train
57 = Clear Bell
58 = Talkbox Bass
59 = Zenith
60 = Chirp Synth
61 = ElectroTuba
62 = ElectroClav
63 = Silver Screen
0 = Lead Bass
---------------------------

这是我的排序方法返回的内容:

T:------[sorted presets]-----
1 = 2nd Harmonium
2 = Acoustic Bass
3 = Bad Actor
4 = Bassonery
5 = Chirp Synth
6 = Clarinets
7 = Clear Bell
8 = Clear Bell
9 = ElectroClav
10 = ElectroClav
11 = ElectroTuba
12 = ElectroTuba
13 = Fat Clav
14 = Glass Harp
15 = Horn Ensemble
16 = Hudi-gurdi
17 = Knell
18 = Kora
19 = Light Bulb
20 = Marxophone
21 = More Quacking
22 = Mountain Home
23 = Obese Clav
24 = Oboid Jazz
25 = Panorama
26 = Quacking
27 = Rayong
28 = Saturated Ping
29 = SheenPad
30 = Showdown
31 = Silent Movie
32 = Silent Screen
33 = Silver Bowl
34 = Silver Screen
35 = Soft Koto
36 = Steel String
37 = Talkbox Bass
38 = Thin Pad
39 = Third Man
40 = Tubular Bells
41 = Winwood
42 = Wooden Bars
43 = Zenith
44 = Zithar Pad
45 = alpen drive
46 = alto flute
47 = alto flute
48 = clank
49 = flutar
50 = frippery
51 = fuzz floot
52 = ghost Train
53 = ghost flute
54 = heavy breathing
55 = lowrey
56 = new whirled
57 = quiet place 
58 = red cedar
59 = steampipe
60 = theater flutes
61 = theater flutes 2
62 = treadwell pad
63 = whisper cycle
-----------------------------

我不明白为什么它要分成两组……它并没有让我觉得需要特殊排序方法的数据……但这似乎不是那种问题。

标签: sortinglua

解决方案


毫不奇怪:在 ASCII 和 UTF-8 中,大写字母排在小写字母之前。

要在排序时忽略大小写,请使用

table.sort(sorted, function (a,b) return a:lower()< b:lower() end)

推荐阅读