[英]Lua sort table value ascending
我有一張表,我需要按升序對 sel_notes[i].Pitch 進行排序。
這些是在 MIDI 編輯器中選擇的 MIDI 音符。
sel 備注表:
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
方法。
第一個參數是一個表,第二個(可選)是一個 function,它返回它的第一個參數是否小於第二個參數。
當然還有表格結構比較怪異的問題,所以你需要去掉第一個元素,這是沒有意義的。 最簡單的方法是使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.