Reputation: 59
I have the array:
racers = {}
racers[6] = {plCP = 4, plID= 21}
If I have the value plID=21, is there a way to return the index of racers? (In this case I'd like to return 6.)
I tried building a reverse index, but I'm only really able to get indexes within the table. Here's what I'm trying right now:
local index={}
for i = 1,5 do
for k,v in pairs(racers[i]) do
index[v]=k
end
end
This returns "plID" when I pass the value 21, but I'd like it to return 6.
Upvotes: 1
Views: 39
Reputation: 28958
For every racer in your list check wether the plID equals the id you are looking for.
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))
Upvotes: 1
Reputation: 59
Figured it out.
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
return index[12]
This returns 5, which is the index of racers I was looking for.
Upvotes: 0