I'm making a game, there are rounds, and if there is only one person left in the global table, then the game will make the round end and give them points.
There is a problem, where I have it set up so it will teleport everybody into a match, instead of just the people inside of the table, which means if somebody joins the game after the players have been inserted into the table, but before they have been teleported, they get teleported into the game too.
I have tried to solve this problem, but it didn't work. There are no errors in the output.
Here is the code with the problem, but it's shortened down.
_G.gameplayers = {} for i,v in pairs(game.Players:GetPlayers()) do -- Iterates through a table of online players if v ~= nil then table.insert(_G.gameplayers, v.Name) -- Puts them in the table end end local spawns = chosenMap:WaitForChild('Spawns'):GetChildren() for _, player in pairs(game.Players:GetPlayers()) do if _G.gameplayers[player] and player and #spawns > 0 then end end
The part that I tried to get the players in the table is on line 10, _G.gameplayers[player]
Any help is appreciated, and if more of my code is required, let me know. Thanks.
Hi mosskil123 I must first comment that your question is formatted and explained beautifully so that it's understandable and informative. :D
The problem is that when on line 10 (like you said) you use _G.gameplayers[player]
in the if statement, you are checking for a key in the table with the player's metadata, not a value. See here for more documentation on keys and values.
What you want to do is to check if a value exists in a table. This is tricky business in lua. Here's how you do it.
function contains(mytable, myvalue) for i, v in ipairs(mytable) if v == myvalue then return true end end return false end _G.gameplayers = {} for i,v in ipairs(game.Players:GetPlayers()) do -- Iterates through a table of online players table.insert(_G.gameplayers, v) -- Puts them in the table end local spawns = chosenMap:WaitForChild('Spawns'):GetChildren() for _, player in ipairs(game.Players:GetPlayers()) do if contains(_G.gameplayers, player) and player and #spawns > 0 then print("Do something") end end
BUT this is a bad structure to go for. One alternative that I see here is to loop through _G.gameplayers and do our checks while looping through that array.
_G.gameplayers = {} for i,v in ipairs(game.Players:GetPlayers()) do -- Iterates through a table of online players table.insert(_G.gameplayers, v.Name) -- Puts them in the table end local spawns = chosenMap:WaitForChild('Spawns'):GetChildren() for _, player in ipairs(_G.gameplayers) do if player and #spawns > 0 then print("Do something") end end
tl;dr : check the second solution.
EDIT: Stole edits from the comments below. See there for more explanation about not using v~=nil
and not entering v.Name
into tables, rather just the player object ... etc.