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

Problems with a table and looping. How can I fix this?

Asked by
C1RAXY 81
5 years ago
Edited 4 years ago

Hello, great community.

The script that I'm wanting to make is simply that I choose some friends to get some powers on my game when they join. But it seems that Roblox doesn't recognize the table and doesn't fire the loop to my friends. I don't get anything on the output, it just doesn't do anything.

01Friends = {"Roblox";"MasterRoblox43";"silversiverbas"}
02 
03game.Players.PlayerAdded:Connect(function(a)
04    print("Checking "..a.Name) -- It only prints.
05            for i,v in pairs (game.Players:GetChildren()) do
06                if v.Name == Friends then
07                for i = 1,3 do
08 
09                -- Code of the powers
10 
11            end
12        end
13    end
14end)

What am I doing wrong, I think it's the table or the if v.Name == Friends then I'm not sure, if you know the issue, please let me know.

In the output, it only prints the print("Checking "..a.Name) but when my friends join it just say "check Friend name" and don't fire the loop that how it's supposed to be.

2 answers

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

You've just got the application of the for loop mixed up. What you're currently doing is checking if each player in Players's name is equal to a table (which will always return false) instead of checking if the player's name is within the table.

You can switch the parameters of the for loop as follows:

01Friends = {"Roblox";"MasterRoblox43";"zoogizile";"silversiverbas";"zoogizile"}
02 
03game.Players.PlayerAdded:Connect(function(a)
04    print("Checking "..a.Name) -- It only prints.
05    for i, v in pairs(Friends) do
06        print(v) --[[ will print:
07            Roblox
08            MasterRoblox43
09            zoogizile
10            ...
11        ]]
12        if a.Name == v then -- check if the player that joined is equal to one of the names in Friends
13            -- give powers
14            break -- stop the loop here so it doesn't keep computing after we've found the right player
15        end
16    end
17end)

Please accept this answer if it helps! Thanks!

0
Thanks for the nice quality of the answer, really helped me alot, thanks man! C1RAXY 81 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

Building off of what HollowMariofan said:

You can simplify your script by transforming your list into a dictionary for fast lookup:

1local friends = {"Roblox", "MasterRoblox43", "etc"}
2for i = 1, #friends do
3    friends[friends[i]] = true
4end
5game.Players.PlayerAdded:Connect(function(player)
6    if friends[player.Name] then
7        -- give powers
8    end
9end)

If this syntax is unfamiliar to you, read through http://lua-users.org/wiki/TablesTutorial

0
I will check how syntax work, thanks for sharing the link. C1RAXY 81 — 5y

Answer this question