The error must have occured when there were no lights on workspace. I solved the error and I also made it so it detects if the light is enabled or not.
local RunService = game:GetService("RunService")
local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local hum = char:WaitForChild("Humanoid")
local sound = workspace.Heartbeat
local maxDist = 100
local lights = {}
RunService.Heartbeat:Connect(function()
for i,v in pairs(workspace:GetDescendants()) do -- scans through workspace
local light = v:FindFirstChildWhichIsA("Light")
if light ~= nil and v:IsA("BasePart") then
if light.Enabled == true then
local dist = plr:DistanceFromCharacter(v.Position)
table.insert(lights,dist)
end
end
end
local hasLight = lights[1]
if hasLight == nil then return end
local totalLights = 0
for i,v in pairs(lights) do
totalLights += 1
end
if totalLights > 1 then
table.sort(lights, function(a,b)
return a<b
end)
end
local dist = lights[1]
if dist < maxDist then
if sound.IsPlaying == true then
-- detect if it's playing
sound:Stop()
end
elseif dist > maxDist then
if sound.IsPlaying == false then
-- detects if it's not playing, also fixes the bug
-- that doesn't play the sound as expected
sound:Play()
end
end
lights = {}
end)