When I run this script it doesn’t always replace the player’s old value on the list. I haven’t been able to figure out why. This script only runs once a player gets a new record and it always places the new record in the right spot. Do you guys have any idea why this might be?
function updateTop10(id, map, recTime)
if PlayerData:GetAsync('/'..map..'/TopTen/') == nil then -- Empty List
print("Tryed to replace list ".. map)
local allPlayers = PlayerData:GetAsync('/'..map..'/PlayerStats/')
allPlayers= HttpService:JSONDecode(allPlayers)
local temp10 = {}
function switch(j, newPlayer)
if j<11 then
if temp10[j] ~= nil then
local fatL = temp10[j]
temp10[j] = newPlayer
-- print("changed index ".. j.." to user ".. newPlayer.UserId)
switch(j+1, fatL)
else
temp10[j] = newPlayer
print("new index "..j)
end
end
end
for i,v in pairs(allPlayers) do
local success, result = pcall (function()
local count =1
local replaced = false
v.UserId = i
-- print("checking user ".. i )
while count<11 and replaced == false do
if temp10[count] == nil then
temp10[count] = v
-- print("found nil "..count)
break
elseif temp10[count].Time > v.Time then
switch(count, v)
-- print("attempted to switch")
break
end
count = count+1
end
end)
if result ~= nil then
print("updating the list failed ".. result)
end
end
--temp10.Updated = os.date()
--print(temp10[1].." is first ")
local sendable =
PlayerData:SetAsync('/'..map..'/TopTen/', HttpService:JSONEncode(temp10))
print("Top Ten Data was sent")
else
local changed = false
local allPlayers = PlayerData:GetAsync('/'..map..'/TopTen/')
allPlayers= HttpService:JSONDecode(allPlayers)
function switchV2(index, playerId, found, newPlayer)
if index< 10 then
if allPlayers[index] ~= nil then
if playerId == tonumber(allPlayers[index].UserId) and found == false then
allPlayers[index].Time = newPlayer.Time
-- print("past Record")
changed = true
elseif playerId == tonumber(allPlayers[index].UserId) and found == true then
-- print("stopped")
changed = true
else
local holding = allPlayers[index]
-- print("moving Player Down ".. index)
allPlayers[index] = newPlayer
changed = true
switchV2(index+1, playerId, true, holding)
end
elseif found == false then
allPlayers[index] = newPlayer
-- print("NEW INDEX".. index)
changed = true
end
else
-- print("end of list")
end
end
local localPlayer = {UserId = id , Time = recTime, Date = os.time()}
local count = 1
for i,v in pairs(allPlayers)do
count = count +1
if v == nil or v.Time > recTime then
switchV2(i, id, false, localPlayer)
break
end
end
if count < 10 and changed ~= true then
-- print("count not 10")
switchV2(count, id, false, localPlayer)
end
if changed == true then
PlayerData:SetAsync('/'..map..'/TopTen/', HttpService:JSONEncode(allPlayers))
-- print("updated records")
else
-- print("no change detected")
end
-- temp = HttpService:JSONDecode(temp)
end
end