Variable in a while loop doesent update

Title
Main problem is that if i put a print inside the loop, it always prints true, even if the variable outside is set to false

I have basically tried everything at this point:

  • putting the loop inside task.spawn (as well as coroutine)
  • putting a if statement inside to break
local levent = game.ReplicatedStorage.lEvent

levent.Event:Connect(function(cameraenabled)
	if cameraenabled then
		while cameraenabled do
			local Image = script.Parent
			local a = 0.03
			task.wait(a)
			-- more code, doesent change "cameraenabled" variable
		end
	end
end)

Please help

this might be from the other script calling the event.

do you mean that if you set cameraenabled to false inside the loop it keeps on looping anyway?

hm
Basically what I mean is that even if i trigger the “levent” with cameraenabled being set to false, the loop still continued

try printing the variable which is being sent over in the script thats firing the bindable event.

sorry I’m not sure if I understand. do you mean that if you trigger the event with cameraenabled set to true and then you trigger the event again with cameraenabled set to false, the first loop still continues? or do you just mean that you fired the event with cameraenabled set to false and the script thinks its true

I did
Printing the variable right before the if (before the loop) prints it correctly, while printing it inside of the loop always prints “true”, even if I send a “false”

Each time an event is fired, its connected functions are executed in a separate thread. Firing the event with false will not affect previous function calls, but simply generate a new function call with a different context

Oh, thanks for the info

Is there any way I could get around that?

You can set up an upvalue for the loop to use as its condition, that way changes to the upvalue from future function calls can affect previous ones:

local cameraEnabled = false


local function onSetCameraEnabled(enabled: boolean)
    cameraEnabled = enabled

    while cameraEnabled do
        -- ...
    end
end


setCameraEnabled.Event:Connect(onSetCameraEnabled)

(Please try to use concise variable names from hereon)

1 Like

Oh god thanks, it worked
I should probably keep that in mind next time

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.