Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Roblox Table(Arrays) Help?

Basically I want to add players names to a table when they join and remove them when they leave. How do you search through the table and remove the players name when they leave. This is what I have so far.

listofaccounts = {}
function inTable(listofaccounts, item)
    for key, value in pairs(listofaccounts) do
        if value == item then return key end
    end
    return false
end
game.Players.PlayerAdded:connect(function(player)
	local player1 = player.Name
	table.insert(listofaccounts, player1)
end)
game.Players.PlayerRemoving:connect(function(player)
	local player1 = player.Name
	if listofaccounts[player.Name] then
  		table.remove(listofaccounts, inTable(listofaccounts, player.Name))
	end
end)

1 answer

✓ Accepted answer

Here's something that should work:

local playerNames = {}

game.Players.PlayerAdded:connect(function(player)
    playerNames[player.UserId] = player.Name
end)

game.Players.PlayerRemoving:connect(function(player)
    playerNames[player.UserId] = nil
end)

Here's an explanation to what all of this is:

First off, we have this:

local playerNames = {}

That tells Lua we want to create a blank table called playerNames. Notice how we use the keyword local before the name of the variable. Using the local keyword for variables has numerous positive effects.

Next, we have the PlayerAdded event handler:

game.Players.PlayerAdded:connect(function(player)
    playerNames[player.UserId] = player.Name
end)

When the player connects, we add the player's name to the playerNames table with their UserId as the index.

Finally, we have the PlayerRemoving event handler:

game.Players.PlayerRemoving:connect(function(player)
    playerNames[player.UserId] = nil
end)

When a player disconnects, we set the player's name to nil in the playerNames table using the same index as before (their UserId). Setting a value in a table to nil triggers garbage collection, or more simply, removes the entry from the list.

I hope this helped. Good luck!

1 comment

0

Thanks this is perfect and exactly what i was looking for. Couldn't have asked for a better answer.

This discussion is preserved as it was. New answers, comments, and votes are closed.