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
4 years ago
Edited 3 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.

Friends = {"Roblox";"MasterRoblox43";"silversiverbas"}

game.Players.PlayerAdded:Connect(function(a)
    print("Checking "..a.Name) -- It only prints.
            for i,v in pairs (game.Players:GetChildren()) do
                if v.Name == Friends then
                for i = 1,3 do

                -- Code of the powers

            end
        end
    end
end)

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 4 years ago
Edited 4 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:

Friends = {"Roblox";"MasterRoblox43";"zoogizile";"silversiverbas";"zoogizile"}

game.Players.PlayerAdded:Connect(function(a)
    print("Checking "..a.Name) -- It only prints.
    for i, v in pairs(Friends) do
        print(v) --[[ will print:
            Roblox
            MasterRoblox43
            zoogizile
            ...
        ]]
        if a.Name == v then -- check if the player that joined is equal to one of the names in Friends
            -- give powers
            break -- stop the loop here so it doesn't keep computing after we've found the right player
        end
    end
end)

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 — 4y
Ad
Log in to vote
0
Answered by 4 years ago

Building off of what HollowMariofan said:

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

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

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 — 4y

Answer this question