I have this part of my script which I go through a table and if the player’s user Id matches one of the Id’s (key) in the table, it awards a badge:
for rank, d in pairs(data) do
local name = d[1]
local points = d[2]
Id = tonumber(name)
ranknew = rank
print(Id .. " is ranked #" .. rank)
end
local function speakerAdded(speakerName)
local speaker = ChatService:GetSpeaker(speakerName)
local player = speaker:GetPlayer()
if player and player.UserId == Id and ranknew <= 20 and not badgeService:UserHasBadgeAsync(player.UserId, badgeId) then
badgeService:AwardBadge(player.UserId, badgeId)
print("awarded badge")
end
end
However, the part which is player.UserId == Id does not go through the keys of the table (the variable Id) and try to match it. What am I doing wrong?
You have a for loop which loops through everything and prints it once. After that you have a function. The function does not loop anything, instead if checks if a variable Id (which will have the value of the last pair in the loop) and ranknew which has the last key.
The issue I believe is that you loop it through once, but you don’t check for it when the function is called.
You could loop through everything first and create a new table which suits your needs better. You could the userId as the key and the rank as the value.
local rankTable = {}
for rank, d in pairs() do
local name = d[1]
local points = d[2]
rankTable[tonumber(name)] = rank
end
The loop above will create a new table rankTable which has the format userid : rank. You may in your if-statement use rankTable[player.UserId] to get the rank of the player.
This worked well… thank you for explaining and for the example, this is what the finished code snippet looked like:
local rankTable = {}
for rank, d in pairs(data) do
local name = d[1]
local points = d[2]
rankTable[tonumber(name)] = rank
print(tonumber(name) .. " is ranked #" .. rank)
end
local function speakerAdded(speakerName)
local speaker = ChatService:GetSpeaker(speakerName)
local player = speaker:GetPlayer()
if player and rankTable[player.UserId] <= 20 and not badgeService:UserHasBadgeAsync(player.UserId, badgeId) then
badgeService:AwardBadge(player.UserId, badgeId)
print("awarded badge")
print(player.UserId .. " is " .. rankTable[player.UserId])
end
end