I am trying to put a stencil buffer in a texture for use in deferred rendering.
I get other embeddings of color and depth with glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[color1], 0);, and the result is correct.

However, when I try to attach my stencil buffer to the texture with glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT ,GL_TEXTURE_2D, textures[stencil], 0);, I get a distorted result, as if the FBO were not clearing their buffers.

I do not know what's the problem. My suspicion is that this is a problem with the stencil texture setting ...
glBindTexture(GL_TEXTURE_2D, textures[stencil]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexImage2D( GL_TEXTURE_2D, 0, GL_STENCIL_INDEX8, 512, 512, 0, GL_STENCIL_INDEX, GL_BYTE, 0);
I have no error codes in my setup, so I don’t understand what the problem is.
EDIT: Maybe I'm doing it wrong. If someone knows how to write a stencil buffer into a texture, I don't care if I write another cod. I just need a method that works.