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

In pairs loop seems not to run through dictionary?

Asked by 3 years ago
Edited 3 years ago

I'm working on a story game, and right now I'm working on the lobby system, where the players join the lobby to get teleported and all that stuff. I have a GUI-based layout where you click buttons to get into each lobby (not physically walking into one like most other story games). My system is that each player is assigned a value in a dictionary, and the dictionary updates when players join or leave. However whenever I loop through the table to check an empty value to assign the player to, it doesn't seem to do that. No errors or anything, just...nothing.

Here is my code:

local players = {
    Player1 = nil;
    Player2 = nil;
    Player3 = nil;
    Player4 = nil;
    Player5 = nil;
    Player6 = nil;
    Player7 = nil;
    Player8 = nil;
}

game.ReplicatedStorage.Chapter1.AddToLobby.OnServerEvent:Connect(function(p)
    print("nsdn")
    for i, v in ipairs(players) do
        print("yee")
        wait()
    end
end)

How do I fix this?

1 answer

Log in to vote
1
Answered by 3 years ago
Edited 3 years ago

Setting a value to nil in a dictionary is the same as removing it entirely, having it not exist, so basically you can visualize:

local players = {
    Player1 = nil;
    Player2 = nil;
    Player3 = nil;
    Player4 = nil;
    Player5 = nil;
    Player6 = nil;
    Player7 = nil;
    Player8 = nil;
}

as this:

local players = {}

Another thing to remember is that ipairs requires order while pairs doesn't. Since a dictionary has no order because like.. they are words... in a table, it won't print.

local players = {
    Player1 = ""
    Player2 = ""
    Player3 = ""
    Player4 = ""
    Player5 = ""
    Player6 = ""
    Player7 = ""
    Player8 = ""
}
game.ReplicatedStorage.Chapter1.AddToLobby.OnServerEvent:Connect(function(p)
    print("nsdn")
    for i, v in pairs(players) do
        print("yee")
        wait()
    end
end)

You can use empty space as an alternative or even a boolean, whatever suits you.

0
well then how do i run through it in order? FirewolfYT_751 223 — 3y
0
so that a player doesn't get assigned spot 7 when spot 3 is vacant FirewolfYT_751 223 — 3y
0
nvm i think i got it. FirewolfYT_751 223 — 3y
Ad

Answer this question