比较lua表中的值

时间:2021-06-15 13:21:02

标签: indexing lua compare

我需要帮助。我有一张这样的桌子:

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

1 个答案:

答案 0 :(得分:1)

您可以使用具有负步长的数字 for 循环返回表中,从前一个元素开始。检查 achanaseq 字段是否存在,然后将它们与当前条目的 dchandseq 字段进行比较。

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 条目并且您的索引在范围内等等...

相关问题