Messing with While-loop

I have this round base 2D game. I came across a logic problem.

What I want to achieve is like this:

button.MouseButton1Click:Connect(function()
    stop()
end)

while game_ended == false do
    -- long game logic here which takes time to continue the while-loop.
end

function stop()
    game_ended = true
end

I want to entirely stop the while-loop while it’s running in the middle of functioning so that I can restart the game. Is this possible? or is there any other way around?

You can use the task library to create and then cancel/kill threads.
For example,

local thread = task.spawn(function()
	while task.wait() do
		-- long game logic here which takes time to continue the while-loop.
		
	end
end)

local function stop()
	game_ended = true
	task.cancel(thread)
end

script.Parent.MouseButton1Click:Connect(function()
	stop()
end)

PS use local functions instead of globals

1 Like

I used global functions because I want to still call it from below the code.

any suggestions to improve that?

Anyways, thank you for the solutions you’ve provided.

local functions are faster for Lua to access due to the way they are allocated in memory

Can’t you just move the stop function above the loop? or perhaps load it in from a module script?

It won’t really affect performance that much in this case, but it’s still good practice to avoid using global functions wherever possible

1 Like

I did the local functions but, I use functions to call another, then the problem comes up because some other functions are below or above vice-versa. regarding module-scripts, I haven’t tested it yet.

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