Garry's mod attempt to call method 'team' (a nil value)

hello everyone
im having a problem while trying to program a custom gamemode
this error always pops up “20: attempt to call method ‘team’ (a nil value)”

here’s my lua code



function ply:SetupTeam( ply, n )
	if ( not teams[n] ) then return end
	team1 = team.GetPlayers( 0 )
	team1 = table.Count(team1)
	team2 = team.GetPlayers( 1 )
	team2 = table.Count(team2)
	if ( ply:team() == NULL and team1 == 1 and team2 == NULL or team2 > team1 or team2 == team1  ) then 
	ply:SetTeam(1) 
	elseif( team1 == null and team2 == 1 and ply:team() == NULL ) then 
	ply:SetTeam(0) 
	end
	if ( ply:team() == NULL and team1 == NULL and team2 == NULL ) then
	self:SetTeam( n )
	self:SetPlayerColor( teams[n].color )
	self:SetHealth( 100 )
	self:SetMaxHealth( 100 )
	self:SetWalkSpeed( 250 )
	self:SetRunSpeed( 500 )
	self:GiveWeapons( n )
	if( n == 1 ) then
	self:SetModel( "models/player/model.mdl" )
	elseif( n == 0 ) then 
	self:SetModel( "models/player/model.mdl" )
	end
	end
end


Can you post the whole file? This code looks really wrong

sure here’s the link for the whole file

https://mega.nz/#!yUBXQJ6K!vBXnmT_lFoYoZpvcRa0VlzICkFbZ9zikdeDzhu3JOSY

Note: the point of this code pick someone random ( one person ) then set his team to 1 and everybody else would be team 2