【问题标题】:Lua sort table value ascendingLua排序表值升序
【发布时间】:2019-11-18 15:32:30
【问题描述】:

我有一张表格,我需要对 sel_notes[i].Pitch 进行升序排序。
这些是在 midi 编辑器中选定的 midi 音符。

选择备注表:

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

sel_notes 表使用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,
   },
}

如果我这样做,我需要对表格进行排序

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

那么我将能够更改音符的音高值,使其与另一个具有和弦音符的表格的音高值相匹配。 所以: 52 到 55 节距 第 58 至 59 节 间距 63 到 62

【问题讨论】:

  • 使用 table.sort(sel_notes, function (a,b) return a.Pitch .. a.Idx < b.Pitch .. b.Idx end ) 并可能检查 nil。
  • 不错的故事,但你的问题是什么? ;)

标签: sorting lua midi


【解决方案1】:

您可以使用table.sort 方法。

第一个参数是一个表,第二个(可选)是一个函数,返回它的第一个参数是否小于第二个。

当然还有表格结构比较怪异的问题,所以你需要去掉第一个元素,这是没有意义的。最简单的方法是使用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

【讨论】:

    猜你喜欢
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多