Help with understanding script logic

Assuming that the credentials are properly filled in a server script:

local RunService = game:GetService("RunService")
local remoteEvent = game:GetService("ReplicatedStorage"):WaitForChild("RemoteEvent")

local function ClientEvent(player)
wait(1)
end

RunService.Heartbeat:Connect(function(step)
print("Test")
end)

remoteEvent.OnServerEvent:Connect(ClientEvent)

If I called the client event, would the script stop printing “Test” for one second, since wait is yielding?

This is something I’ve really wanted to know for ages, this still confuses me.

No. Event listeners are called in separate threads so there won’t be any interrupting going on. Though, why didn’t you test this yourself? You would have gotten an answer that way.

1 Like

Facepalm
Thats a really good point. My apologies…
Thank you very much @sjr04 xD

Quite the opposite, in fact. While Lua “pretends” (or simulates? not sure of the terminology) to be multithreaded, it can only actually run another thread while the first one is yielding, like the wait(1) in this example.

3 Likes

@sjr04 I have tested it out
test example.rbxl (20.9 KB)
@posatta So is what’s going in is that the script would just keep running back and forth between the two as if it can only process one at a time, but it gives the illusion of running both at the same time?

Yeah, exactly right. When one thread yields (delays), it gives the others a chance to run until their next yield, and so on.

3 Likes

So I am assuming that is also why while statements require a wait somewhere or else studio will just go “poof”.
Do you know anything about for loops? Such as if for loops will yield after it loops once or something? Or will it continue running that thread until the loop ends?
Btw, thank you so much for the help!

1 Like

Yeah, it’ll continue running just like a while loop. You can try this yourself:

for i = 1, math.huge do -- math.huge = infinitely high number
	local x = 4 * 4
end

(It should timeout.)

3 Likes

Thank you very much!
Gosh, I’m sorry for asking another question but I’m so glad for these responses.
If I require a module script, would the script treat the modulescript as a separate script or would just act as if it’s pasting code into the script?

I can’t test right now, but my assumption would be that it’ll yield the main script as though the code was copy-pasted when it’s first required and when you call any of the module’s functions.

3 Likes

The couple of questions I’ve been having for almost a decade are now quenched. Thank you very much!