It’s an important question for entomologists and other ecologists, who often collect moths using ‘light traps’. However, there’s not one generally agreed answer. Of the hundreds of thousands of moth species, many don’t gather around lights. We tend to notice those that do, especially when they self-immolate. Even these differ: some spiral inwards, others head straight, but then orbit. The time of night and moth’s gender also make a difference.
There’s some suggestion males mistake the heat and scent of candles for females. The Moon’s position, phase and visibility also have an effect, and most explanations assume certain moths have evolved to use natural light for orientation by night. One old hypothesis involves moths (partially) navigating by maintaining an acute angle to the Moon, meaning they spiral towards a fixed artificial light. Alternatively, moths may head skywards towards natural light, to escape predators or before high-altitude voyages. Once close to a bright light, moths probably become blinded, disorientated or confused by optical illusions (called ‘Mach bands’) that seem to show safe darker areas near the light’s edge.
a better explanation
A better explanation I received is that moths navigate relative to the position of the moon. So at any minute some moths may be trying to fly south, some east etc. The moths who's heading happens to be more toward the moon will consequently spiral in towards a fixed light.
It just happens that we only notice the moths that have been navigating in a moonward direction.
So the answer is, they aren't attracted to light at all, but they do try and use the moon to maintain their bearings.