While loop isnt working?

this should be working, and it isnt, iv tried different ways of making this work, the only print that works is “lightning” but the loops do not

local LightningBolt = require(game.ReplicatedStorage:WaitForChild("Lightning"))

local rain = false
local thunderstorm = false

game.Lighting.Weather.Changed:Connect(function(val)
	if val == "Rain" then
		rain = true
		thunderstorm = false
	end
	if val == "Thunderstorm" then
		print("lightning")
		thunderstorm = true
		rain = false
	else
		rain = false
		thunderstorm = false
	end
end)

while thunderstorm == true do
	print("is thunderstorm")
	local waittime = math.random(3,20)
	task.wait(waittime)
	print("waited for bolt")
	thunderstormboltfunction()
	print("MADE THUNDERSTORM LIGHTNING")
end

while rain == true do
	local waittime = math.random(20,80)
	task.wait(waittime)
	local random = math.random(1,2)
	if random == 2 then
		thunderstormboltfunction()
	end
end

That is because the loop will only run once. Given that the thunderstorm variable starts at the value of false, the first loop will not iterate even ONCE and it’ll move onto the next one. Since rain is also false, the second loop ALSO terminates immediately.

You would have to either fuse the loops into one and use os.clock() to delay the thunderbolts, OR start a new loop in the Changed connection, which will be terminated once the value is changed again.

I will go for the second option here, for the sake of simplicity. Ideally you would use RunService connections.

-- we use lastUpdate to determine whether should the loop continue
local lastUpdate = 0
local state = "N/A"

-- creates dictionary of functions
local weatherStates = {}

-- define rain behaviour
function weatherStates.Rain(startedAt)
    while lastUpdate == startedAt do
        task.wait( math.random(20, 80) )
        if math.random(1, 2) == 2 then
            thunderbolt()
        end
    end
end

-- define thunderstorm behaviour
function weatherStates.Thunderstorm(startedAt)
    while lastUpdate == startedAt do
        task.wait( math.random(3, 20) )
        thunderbolt()
    end
end

game:GetService("Lighting").Weather.Changed:Connect(function(value)
    state = val
    lastUpdate = os.clock()

    if weatherStates[val] then -- is there anything at the index of value?
        weatherStates[val](lastUpdate) -- if so, call the function there
    end
end)

i got this to work, but it causes a script timeout?

while wait() do
	if thunderstorm == true then
	print("is thunderstorm")
	local waittime = math.random(3,20)
	task.wait(waittime)
	print("waited for bolt")
	thunderstormboltfunction()
	print("MADE THUNDERSTORM LIGHTNING")
	else
		if rain == true then
	local waittime = math.random(20,80)
	task.wait(waittime)
	local random = math.random(1,2)
	if random == 2 then
		boltfunction()
		end
		end
	end
end

The script shouldn’t do that. It’s likely one of your two functions - thunderstormboltfunction or boltfunction.