如何解决比较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 条目并且您的索引在范围内等等...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。