Lua 排序 table 值升序

Lua sort table value ascending

我有一个 table 我需要排序 sel_notes[i].Pitch to ascending order.
这些是在 midi 编辑器中选择的 midi 音符。

sel 笔记 table :

sel_notes = {}
sel_notes[pitch] = {Pitch = pitch, Idx = i}
sel_notes[i] = {Pitch = pitch, Idx = i}

sel_notes table 使用 table.save-1.0.lua:

return {
-- Table: {1}
   {
      [64]={2},
      [65]={3},
      [66]={4},
      [67]={5},
      [52]={6},
      [69]={7},
      [68]={8},
      [55]={9},
      [56]={10},
      [57]={11},
      [58]={12},
      [59]={13},
      [60]={14},
      [61]={15},
      [62]={16},
      [63]={17},
   },
-- Table: {2}
   {
      ["Pitch"]=63,
      ["Idx"]=64,
   },
-- Table: {3}
   {
      ["Pitch"]=52,
      ["Idx"]=65,
   },
-- Table: {4}
   {
      ["Pitch"]=58,
      ["Idx"]=66,
   },
-- Table: {5}
   {
      ["Pitch"]=52,
      ["Idx"]=67,
   },
-- Table: {6}
   {
      ["Pitch"]=52,
      ["Idx"]=67,
   },
-- Table: {7}
   {
      ["Pitch"]=58,
      ["Idx"]=69,
   },
-- Table: {8}
   {
      ["Pitch"]=63,
      ["Idx"]=68,
   },
-- Table: {9}
   {
      ["Pitch"]=52,
      ["Idx"]=55,
   },
-- Table: {10}
   {
      ["Pitch"]=58,
      ["Idx"]=56,
   },
-- Table: {11}
   {
      ["Pitch"]=63,
      ["Idx"]=57,
   },
-- Table: {12}
   {
      ["Pitch"]=58,
      ["Idx"]=69,
   },
-- Table: {13}
   {
      ["Pitch"]=63,
      ["Idx"]=59,
   },
-- Table: {14}
   {
      ["Pitch"]=52,
      ["Idx"]=60,
   },
-- Table: {15}
   {
      ["Pitch"]=52,
      ["Idx"]=61,
   },
-- Table: {16}
   {
      ["Pitch"]=63,
      ["Idx"]=62,
   },
-- Table: {17}
   {
      ["Pitch"]=63,
      ["Idx"]=68,
   },
}

我需要 table 排序,所以如果我这样做

for 1 = 1, 15 do
  note = sel_notes[i].Pitch
  index = sel_notes[i].Idx
  print(note,index)
end

我会得到这个:

52 55
52 60
52 61
52 65
52 67
58 56
58 58
58 63
58 66
58 69
63 57
63 59
63 62
63 64
63 68

这样我就可以更改音符的音高值,使它们与另一个具有和弦音符的 table 的音高值相匹配。 所以: 球场 52 至 55 球场 58 至 59 音高 63 到 62

您可以使用table.sort方法。

第一个参数是 table,第二个(可选)是一个函数,它 returns 它的第一个参数是否小于第二个参数。

当然还有table结构比较奇怪的问题,所以你需要去掉第一个元素,这是没有意义的。最简单的方法是使用 table.remove.

所以像

local function sort(tab)
   table.remove(tab, 1) -- Remove first element
   table.sort(tab, function(a, b)
      return true -- Your sorting criterion goes here
   end)
end