Lua table值匹配查询:Dissector场景下查找对应历史条目索引
解决方案
方案1:直接遍历历史条目(适合数据量较小的场景)
不需要修改你现有的dict结构,直接从1遍历到当前索引的前一位,逐个匹配条件即可:
-- 参数说明:dict 是你存储条目的表,current_idx 是当前处理的位置索引 function findMatchedHistoryIndex(dict, current_idx) local current_entry = dict[current_idx] -- 匹配当前条目为ACK类型、查找对应历史DATA条目的场景 if current_entry.achan and current_entry.aseq then for i = 1, current_idx - 1 do local hist_entry = dict[i] if hist_entry.dchan and hist_entry.dseq and hist_entry.dchan == current_entry.achan and hist_entry.dseq == current_entry.aseq then return i end end end -- 匹配当前条目为DATA类型、查找对应历史ACK条目的场景(适配你给出的示例需求) if current_entry.dchan and current_entry.dseq then for i = 1, current_idx - 1 do local hist_entry = dict[i] if hist_entry.achan and hist_entry.aseq and hist_entry.achan == current_entry.dchan and hist_entry.aseq == current_entry.dseq then return i end end end -- 未匹配到返回空 return nil end
调用findMatchedHistoryIndex(dict, 6)即可得到返回值1,符合你的示例预期。
方案2:新增索引表优化查询(适合高频率查询、数据量大的Dissector场景)
如果你的dict会存储大量条目,每次遍历历史的效率会很低,你可以新增索引表,每次存新条目的时候提前构建索引,查询时间复杂度可优化到O(1):
local dict = {} -- 新增两个索引表,用chan+seq拼接为唯一key,存储对应条目索引 local d_seq_index = {} local a_seq_index = {} -- 封装新增条目的方法,自动更新索引 function addNewEntry(entry) local idx = #dict + 1 dict[idx] = entry if entry.dchan and entry.dseq then local key = entry.dchan .. "|" .. entry.dseq d_seq_index[key] = idx end if entry.achan and entry.aseq then local key = entry.achan .. "|" .. entry.aseq a_seq_index[key] = idx end return idx end -- 快速查询匹配的历史索引 function fastFindMatchedIndex(current_idx) local current = dict[current_idx] -- 当前是ACK,查对应DATA索引 if current.achan and current.aseq then local key = current.achan .. "|" .. current.aseq return d_seq_index[key] end -- 当前是DATA,查对应ACK索引 if current.dchan and current.dseq then local key = current.dchan .. "|" .. current.dseq return a_seq_index[key] end return nil end
内容的提问来源于stack exchange,提问作者Glupschi
相关产品推荐
相关产品推荐

