因此,如果您需要从chords 中选择一个随机的chord,以便chords[index].Name == chord_name 和您的索引一个接一个,例如:1、2、3、4、5(而不是例如:52、96 , 121) 你可以这样做:
chord_name = "Cm7b5"
index = math.random(#chords)
while chords[index].Name ~= chord_name do
index = math.random(#chords)
end
time = chords[index].Start
(请注意,我没有选择和弦,而是 .Start 时间,正如您的示例所示。)
但是,如果您有大量数据并且只有少数数据有.Name == chord_name,则这很有可能(几乎)无限循环。
因此,确保对math.random() 的单次调用将给我们一个明确的答案(索引)是一个好主意。
chord_name = "Cm7b5"
--we create an empty table
indexes = {}
--and store all indexes that fulfil the condition chords[index].Name == chord_name
for index, chord in pairs(chords) do
if chord.Name == chord_name then
table.insert(indexes, index)
end
end
--now we can randomly select from this table
index = indexes[math.random(#indexes)]
--which will always yield an index pointing to a chord with .Name == chord_name
time = chords[index].Start
请注意,使用pairs(chords) 还允许从有孔的表格中选择和弦(即{[1] = "a", [5] = "b", [16] = "c"})。
另一方面,如果您有大量(可能是数百万或 100k)数据,则后一种解决方案可能会出现问题。迭代整个表并选择匹配的名称并基于它创建一个新表将非常耗时和消耗内存。