I know this is a really simple question, but it really caught my attention. If i do this:
local function func_name(value) -- do something end game.Players.PlayerAdded:Connect(function(plr) func_name(plr) end)
This code will listen every time a player joins, and fire a function.
But my question is: If two players join almost at the same time, and the second player join while the function is being run, would the function fire only once or system would wait until the function called first is finished?
It would fire twice of course. Events run every time they are called, so one player joining would fire it once, and another player joining would fire it again.
Edit: I'd recommend writing your function like this to make it run when the other has finished.
local function func_name(value) -- do something end game.Players.PlayerAdded:Connect(function(plr) repeat wait(0.1) until plr.Character -- will yield until the player fully loads in func_name(plr) end)
From what I know, Roblox is single threaded, which is why running while true do end
would hang your game. Before understanding why Roblox would wait for the first function to finish, you need to understand threads.
Because Roblox is not multithreaded, threads don't actually run at the same time. Instead, the Roblox thread manager splits up the code in each thread and runs those parts from each thread. Whenever a thread uses a yielding function (eg: wait
), Roblox starts running another thread and keeps going through other threads until the yielding function completes. (Note that Roblox continues the thread its currently running until it yields to start the thread again.
Here's an example. Thread A runs an instruction and then yields for 1 second. Thread B runs stuff which takes 2 seconds to execute before yielding again. Thread A resumes 2 seconds after it stopped.
The answer to your question is that, assuming func_name doesn't yield, Roblox would wait for func_name to finish before calling it again with the second player. If func_name yields, you can use the above information to figure out what would happen.
Also, as a side note, you should connect to the function directly instead of creating a function just to call another function like PlayerAdded:Connect(func_name)