首页 > 解决方案 > 比较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

标签: indexingluacompare

解决方案


您可以使用具有负步长的数字 for 循环从前一个元素开始返回表中。检查 achanaseq字段是否存在,然后将它们与当前条目的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 条目并且您的索引在范围内等等......


推荐阅读