Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Trying to assign players to teams, but I receive a nil value. Any help?

Hi, I'm working on a game where one player is selected as an infected, and must infect other players. I'm trying to find a way to put each players onto their given teams, but I just receive this error:

10:05:58.760 - ServerScriptService.Script:9: attempt to index field '?' (a nil value)

I checked, and I'm not quite sure what I did wrong? I'm still fairly new to coding in Lua, and any help is appreciated.

Here is my code:

local TotalPlayers = {}
local Survivors = {}
local Infected = {}

local GameStarted = false

function AssignTeams()
	for i = #Survivors,1 do
		Survivors[i].TeamColor = BrickColor.new("Deep blue")
	end
	
	for a = #Infected,1 do
		Infected[a].TeamColor = BrickColor.new("Bright green")
	end
end

function GameLoading()
	TotalPlayers = game.Players:GetPlayers()
	local val = math.random(1,#TotalPlayers)
	Infected[1] = TotalPlayers[val]
	local Counter = 1
	for i = #TotalPlayers,1 do
		if TotalPlayers[i].UserId ~= TotalPlayers[val].UserId then 
			print("Not Infected")
			Survivors[Counter] = TotalPlayers[i]
			Counter = Counter + 1
			print(#Survivors)
		end
	end
	AssignTeams()
end



function StartIntermission()
	print "Starting intermission..."
	for a = 10,0,-1 do
		print(a)
		wait(1)
	end
	print "Ending intermission"
	GameLoading()
end

while true do
	wait(0.1)
	local playerlist = game.Players:GetPlayers()
	if #playerlist <= 1 then
		print "Not enough players."
	elseif #playerlist >= 2 then
		if GameStarted == false then
		GameStarted = true
		print "Enough players."
		StartIntermission()
		end
	end
end

4 comments

0

check the loop for i = #TotalPlayers,1 do ?

0

It's not printing, I don't think I can really check it until I fix the error on Line9.

0

shouldn't it be for i = 1, #TotalPlayers do? That would make logical sense, wouldn't it?

0

Let me check it, sorry, I'm still not completely used to Lua, lol.

1 answer

✓ Accepted answer

I see your loops looks wrong.

Example read comments.

--The current loop
 for i = #Survivors,1 do
        Survivors[i].TeamColor = BrickColor.new("Deep blue")
    end

--If you increment thruw it lets say #Survivors is 10 and you want to go down one
--I added -1 so it starts at 10 ends at one and goes one down each loop 
 for i = #Survivors,1,-1 do
        Survivors[i].TeamColor = BrickColor.new("Deep blue")
    end

--If you want to increment
--So if  #Survivors is 10 it starts at one then goes up to 10
for i = 1, #Survivors  do
        Survivors[i].TeamColor = BrickColor.new("Deep blue")
    end

2 comments

0

Thank you, this fixed it.

0

Cool did you change each loop.

This discussion is preserved as it was. New answers, comments, and votes are closed.