Help with table.remove

I wanted to make sure that each player was given a different job and that the job that was already randomly selected was removed from the TABLE, so that the next player could not get it. I tried something but the next player can still get the same job

for _, player in pairs(game.Players:GetPlayers()) do
mapstable = {
“Office”,
“Dj”,
“test”
}
local randomwork = mapstable[math.random(1,#mapstable)]
mapstable[randomwork] = nil
print(player.name,“got”,randomwork)
player.PlayerGui.ScreenGui.work.Text = randomwork
end

2 Likes

You’re using an array not a dictionary. So instead of mapstable[randomwork] = nil you would want to use table.remove(mapstable, randomWork)

1 Like

mapstable is redefined and therefore setting an index nil wouldn’t do anything as such.
Also, randomwork is the value of that random index you picked, not the actual index itself.

Here’s how you can do it via table.remove:

local mapstable = {
   "Office",
    "DJ",
    "Test"
}

for _, player in ipairs(game:GetService("Players"):GetChildren()) do --// You should use ipairs for iterating through arrays (ordered and much faster)
    local randomIndex = math.random(#mapstable) --// If one argument is given then math.random will pick a random number between [1, n]
    local randomWork = mapstable[randomIndex] --// Index the random picked index
    player.PlayerGui.ScreenGui.work.Text = randomWork --// You should really be doing this via a RemoteEvent, anyhow
    table.remove(mapstable, randomIndex) --// Remove the index from the table
end

FYI: You should format your code when posting it on the DevForums, it makes it easier to read and help you.

```
Code here
```

5 Likes