返回一个表数组的索引

我有一个数组:

racers = {}
racers[6] = {plCP = 4, plID= 21}

如果我有值 plID=21, 有办法返回 racers 的索引吗? (在这种情况下,我想返回 6。)

我试图创建一个反向索引,但我只能在表内获取索引。 这是我现在尝试的:

local index={}
for i = 1,5 do
    for k,v in pairs(racers[i]) do
       index[v]=k
    end
end

这会返回“plID”,当我传递值 21 时,但是我希望它返回 6。

点赞
用户9589907
用户9589907

找到了。

racers = {}
racers[1] = {plCP = 4, plID= 21}
racers[2] = {plCP = 2, plID= 4}
racers[3] = {plCP = 6, plID= 5}
racers[4] = {plCP = 222, plID= 7}
racers[5] = {plCP = 6, plID= 12}

local index={}
for i,d in pairs(racers) do
for k,v in pairs(racers[i]) do
   index[v]=i
end
end

返回 index[12] 的值为 5,这就是我所寻找的 racers 的索引值。 
2018-04-04 07:51:09
用户2858170
用户2858170

对于你名单中的每个赛车手,请检查plID是否等于您要查找的id。

local racers = {}
racers[1] = {plCP = 4, plID= 21}
racers[2] = {plCP = 2, plID= 4}
racers[3] = {plCP = 6, plID= 5}
racers[4] = {plCP = 222, plID= 7}
racers[5] = {plCP = 6, plID= 12}

function getRacerIndexById(racerList, id)
      for index, racer in ipairs(racerList) do
        if racer.plID == id then
          return index
        end
      end
    end

print(getRacerIndexById(racers, 12))
2018-04-04 09:25:31