在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

基本上我是在一个解析器中使用它的,所以我不知道索引,除了我现在所“处于”的位置。

所以我想要的是:

如果正在“处于”的"aseq"与已经保存到表中的过去位置处的“dseq”值相同,并且“achan”和“dchan”相同,则应返回相同“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的“achan”相同,并且位置6的“dseq”与位置1的“aseq”相同。因此,我想得到位置1。

点赞
用户2858170
用户2858170

你可以使用负的步长数值来进行数值式的 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 条目中,而且你的索引是在有效范围内等等。

2021-06-15 13:50:17