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:

01local players = {
02    Player1 = nil;
03    Player2 = nil;
04    Player3 = nil;
05    Player4 = nil;
06    Player5 = nil;
07    Player6 = nil;
08    Player7 = nil;
09    Player8 = nil;
10}
11 
12game.ReplicatedStorage.Chapter1.AddToLobby.OnServerEvent:Connect(function(p)
13    print("nsdn")
14    for i, v in ipairs(players) do
15        print("yee")
16        wait()
17    end
18end)

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:

01local players = {
02    Player1 = nil;
03    Player2 = nil;
04    Player3 = nil;
05    Player4 = nil;
06    Player5 = nil;
07    Player6 = nil;
08    Player7 = nil;
09    Player8 = nil;
10}

as this:

1local 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.

01local players = {
02    Player1 = ""
03    Player2 = ""
04    Player3 = ""
05    Player4 = ""
06    Player5 = ""
07    Player6 = ""
08    Player7 = ""
09    Player8 = ""
10}
11game.ReplicatedStorage.Chapter1.AddToLobby.OnServerEvent:Connect(function(p)
12    print("nsdn")
13    for i, v in pairs(players) do
14        print("yee")
15        wait()
16    end
17end)

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