So I have a serverscript in ServerScriptService, and it will basically just loop through a players friends and add their UserId to a table called PlayersFriends. But I am scared because what if, I am looping through the players friends and putting them into the table and then running all the checks and stuff I want to do using their UserID’s BUT while doing it, another player joined? Will it just add the player who also joined, friends ID’s to the table? If so, how do I prevent this? (USING A LOCAL SCRIPT IS NOT AN OPTION I CAN DO)
My code
Players.PlayerAdded:Connect(function(player)
local PlayersFriends = {}
local success, page = pcall(function() return Players:GetFriendsAsync(player.UserId) end)
if success then
repeat
local info = page:GetCurrentPage()
for i, friendInfo in pairs(info) do
table.insert(PlayersFriends, friendInfo.Id)
end
if not page.IsFinished then
page:AdvanceToNextPageAsync()
end
until page.IsFinished
end
end)
If another player joined it would simply run that same function again, only the ‘player’ parameter would be the new player that joined and not the previous one. As for code that’s already running when another player joins, it would keep running until it’s finished looping through all the friends.
Each time that function is run, a new PlayerFriends table is created for each player. If you’re trying to store each player’s friends table outside the function though, you’ll need another table to hold all the player friends tables.
local Players = game:GetService("Players")
local playerFriendsTables = {}
Players.PlayerAdded:Connect(function(player)
-- This next line is what the player's friends table will be called
-- in the shared table with all the tables
local friendsUserId = "Friends_" .. player.UserId
local PlayersFriends = {}
local success, page = pcall(function() return Players:GetFriendsAsync(player.UserId) end)
if success then
repeat
local info = page:GetCurrentPage()
for i, friendInfo in pairs(info) do
table.insert(PlayersFriends, friendInfo.Id)
end
if not page.IsFinished then
page:AdvanceToNextPageAsync()
end
until page.IsFinished
end
-- Adding the PlayerFriends table to the second table with all player tables
playerFriendsTables[friendsUserId] = PlayersFriends
end)
The string variable called “friendsUserId” is how we’ll be able to tell which player’s table is which.
absolute legend, one last question, if I were to call a function from players.playeradded, will it also create a new thread for that? or would I have to worry about stuff interfering?