Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Roblox Table(Arrays) Help?

Asked by 9 years ago

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

Log in to vote
0
Answered by 9 years ago

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!

0
Thanks this is perfect and exactly what i was looking for. Couldn't have asked for a better answer. SheePie13 10 — 9y
Ad

Answer this question