How to handle loops?

I have a loop that is constantly checking what the player’s mouse is over, but loops always cause problems with stopping threads and all that fun stuff. So, I’m just wondering how should I handle loops like this?

-- Some functions

function start()
	while task.wait() do -- The loop
		-- not important
	end
end

if (not game:IsLoaded()) then -- Just waiting until the game loads
	game.Loaded:Wait()
end

-- Some other events
start() -- Call the loop
-- Now I can't put anything down here

You can easily fix the problem by running the loop in a coroutine, it would basically run in a separate thread and not influence the rest of the code’s execution.

if (not game:IsLoaded()) then -- Just waiting until the game loads
	game.Loaded:Wait()
end

-- Some other events
coroutine.wrap(function()
    while task.wait() do -- The loop
        -- not important
    end
end)() --Create a new coroutine and instantly execute it
--You can run code here now
1 Like

Works perfectly, thanks, but I am curious if I should continue to check what the player’s mouse is over in a loop, wouldn’t it create lag?

If you’re talking about detecting what GUI element the mouse is hovering then you can simply use the MouseEnter and MouseLeave events and then using a hovering variable which would store the current hovered object and then do whatever you need with that hovered object. If you’re talking about workspace objects then your only options are to constantly checking the mouse target with a loop or you can minimize that by doing it after detecting mouse movement with UserInputService (reccomended) or the respective mouse event (not reccomended as mouse has been supersed by UIS). And anyway yes doing such checks so quickly can cause lag

1 Like

I am checking for stuff in the workspace, so I guess my way works. I tried detecting mouse movement, but if the player hovers over something and walks away without moving their mouse, it’ll trick the code into thinking they’re still hovering over it. Thanks for your help.

1 Like

you can use mouse.Target, mouse.Target is just the BasePart that is targeted by the mouse

example:

local Player = game:GetService("Players").LocalPlayer
local Mouse = Player:GetMouse()

task.spawn(function()
    while task.wait() do
        if Mouse.Target ~= nil then
            -- do whatever
        end
    end
end)

https://create.roblox.com/docs/reference/engine/classes/Mouse#Target