在 lua 中比较 table 中的值
compare values in an table in lua
我需要帮助。我有这样的 table:
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
基本上我在 Dissector 中使用它,所以我不知道索引,除了我现在实际“站立”的索引。
所以我想要的是:
如果“achan”和“dchan”相同,并且我现在站着的“aseq”与已经保存到[中的过去位置的“dseq”值相同=24=] 那么它应该从过去的相同“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 循环返回 table,从上一个元素开始。检查 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
此代码假定您的 table 中没有间隙。您还应该添加一些错误处理,以确保您确实处于 dchan 条目并且您的索引在范围内等等...
我需要帮助。我有这样的 table:
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
基本上我在 Dissector 中使用它,所以我不知道索引,除了我现在实际“站立”的索引。
所以我想要的是:
如果“achan”和“dchan”相同,并且我现在站着的“aseq”与已经保存到[中的过去位置的“dseq”值相同=24=] 那么它应该从过去的相同“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 循环返回 table,从上一个元素开始。检查 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
此代码假定您的 table 中没有间隙。您还应该添加一些错误处理,以确保您确实处于 dchan 条目并且您的索引在范围内等等...