indexing - 比较lua表中的值
问题描述
我需要帮助。我有一张这样的桌子:
local dict = {}
dict[1] = {achan = '7f', aseq='02'} --ACK
dict[2] = {dchan = '7f', dseq='03'} --DATA
dict[3] = {achan = '7f', aseq='03'} --ACK
dict[4] = {dchan = '7f', dseq='04'} --DATA
dict[5] = {achan = '7f', aseq='04'} --ACK
dict[6] = {dchan = '7f', dseq='02'} --DATA
基本上我在解剖器中使用它,所以我不知道索引,除了我现在实际上“站立”的那个。
所以我想要的是:
如果“achan”和“dchan”相同,并且我现在站立的“aseq”与已经保存到表格中的过去位置的“dseq”值相同,那么它应该给我从过去的相同“dseq”值返回索引。
if (dict[position at the moment].achan == dict[?].dchan) and (dict[position at the moment].aseq == dict[?].dseq) then
return index
end
例如:位置 6 的 dchan 与位置 1 的 es achan 相同,位置 6 的 dseq 与位置 1 的 aseq 相同。所以我想找回位置 1
解决方案
您可以使用具有负步长的数字 for 循环从前一个元素开始返回表中。检查 achan
和aseq
字段是否存在,然后将它们与当前条目的dchan
和字段进行比较。dseq
function getPreviousIndex(dict, currentIndex)
for i = currentIndex - 1, 1, -1 do
if dict[i].achan and dict[currentIndex].dchan
and dict[i].achan == dict[currentIndex].dchan
and dict[i].aseq and dict[currentIndex].dseq
and dict[i].aseq == dict[currentIndex].dseq then
return i
end
end
end
此代码假定您的表中没有间隙。您还应该添加一些错误处理,以确保您实际上处于 dchan 条目并且您的索引在范围内等等......
推荐阅读
- javascript - 更新 localStorage 中的单个对象
- vb.net - PictureBox 不应自行触发事件
- ios - Spotify iOS SDK
- javascript - 复选框输入触发 Bootstrap 手风琴折叠事件
- reactjs - 如何实现 react-dnd useDragLayer?
- r - 为什么文本连接不会在管道工 API 运行中持续存在?
- security - 地理定位 WiFi 设备的准确位置
- reporting-services - RDL 报告在导出为 PDF 时显示图像翻转(旋转 180 度)
- reactjs - React 美丽的 DnD- 嵌套列表,但无需在父列表之间拖动
- node.js - 如何处理电子邮件并将其转发到目的地