Code stops at loop (description)

First of all I need to say: I do not need to stop loop.

So I have 3 parts of code:

  • First:
plr.PlayerGui:WaitForChild("Exp").contractsreal.Gradient1.flushed.Text = contract
plr.PlayerGui:WaitForChild("Exp").contractsreal.Gradient1.buy.Text = "Thanks for buying!"
  • Second:
while wait(1) do
	plr.PlayerGui:WaitForChild("Exp").contractsreal.Gradient1.tieme.Text = convert(ftime - os.time())	
end
  • Third:
    some statements: ifs, elseifs

Heres our problem: after code ran while wait loop, it can’t continue to third part of our code, it will endless convert time and set it to our textlabel.
How can we trigger third part?

You could try wrapping the second part of the code with spawn or task.spawn like this:

spawn(function()
while wait(1) do
	plr.PlayerGui:WaitForChild("Exp").contractsreal.Gradient1.tieme.Text = convert(ftime - os.time())	
end
end)

Lua code will execute chronologically from top to bottom, during loops the code will yield and it will not execute past that point until the loop is broken.

The solution to this is called multithreading, you can create a new thread for specific blocks of code to run on that do not yield the script allowing the rest of your script to execute.

There are 2 primary ways of multithreading:
1 - task.spawn
2 - coroutines

Both have effectively the same performance but coroutines give you more control, below are some example use cases

task.spawn example:

local function Looper()
	while true do
		--do stuff
		task.wait(1)
	end
end

task.spawn(Looper)

coroutine example:

local function Looper()
	while true do
		--do stuff
		task.wait(1)
	end
end

local LooperThread = coroutine.create(Looper)
coroutine.resume(LooperThread)

Now in your specific case I would use this code:

local function Looper()
	local Exp = plr:WaitForChild("PlayerGui"):WaitForChild("Exp")
	while true do
		task.wait(1)
		Exp.contractsreal.Gradient1.tieme.Text = convert(ftime - os.time())	
	end
end

task.spawn(Looper)

Also a bonus tip I notice that you use WaitForChild to yield for the same instance multiple times, this can equate to bad performance, I suggest yielding for an instance once and assigning it to a variable and then calling it from a variable from then on, example:

local Exp = PlayerGui:WaitForChild("Exp")
--then call variable Exp to interact with
3 Likes

and here is another way :slight_smile:

local expGui = player.PlayerGui:WaitForChild("Exp")
expGui.contractsreal.Gradient1.flushed.Text = contract
expGui.contractsreal.Gradient1.buy.Text = "Thanks for buying!"

local function Loop()
    task.delay(1, Loop) -- after 1 second call the Loop function
    expGui.contractsreal.Gradient1.tieme.Text = convert(ftime - os.time())	
end
task.delay(1, Loop) -- after 1 second call the Loop function

print("More Code here...")

Thank you so much for fixing the issue. Did not knew about WaitForChild!