User:JulienDethurens/Essays/Wait method

From Legacy Roblox Wiki
Jump to navigationJump to search

You probably all know about the connect method of events, that method you use to connect every event to your functions:

script.Parent.Touched:connect(function(part)
	print(part.Name)
end

But did you know that events had another method, the wait method? I'm sure not many of you know about that method, which yet can be extremly useful and make your code a lot neater and more efficient.

I want to make that wait method more known among users, to help them to improve their code.

The wait method of event waits until the event triggers again and returns any value given by the event.

Yes. That's right. That means you can do this to wait for the player's character to respawn:

game.Players.Player.CharacterAdded:wait()

And yes, you can wait for a part to be touched too:

script.Parent.Touched:wait()

But you can do a lot more too.

Suppose you wanted to wait until a certain child is added to a certain object. You could do it like this:

repeat script.Parent.ChildAdded:wait() until script.Parent:FindFirstChild("Child")

That code would wait until the script's parent contain a child named "Child".

But you can make it even more idiomatic and efficient! Look at this:

repeat until script.Parent.ChildAdded:wait().Name == "Child"

Now, that might look a little complex. Yet, it works. Let me explain it:

I said the wait method would return any value given by the event. The ChildAdded event gives one value: the child that was added. Therefore, repeat until script.Parent.ChildAdded:wait() will be the child that was added and repeat until script.Parent.ChildAdded:wait().Name will be its name. You can therefore, in a boolean expression, both wait until a child is added, and check if that child's name is "Child".

Similarly, because the Changed event returns the name of the property that was changed, you could wait until a certain property is changed. For example, this code would wait until a player's TeamColor changes:

repeat until game.Players.Player.Changed:wait() == "TeamColor"

That's awesome, right?

And, for those interested, here is the equivalent of that using the connect method:

local connection = game.Players.Player.Changed:connect(function(property)
	if property == 'TeamColor' then
		-- Code to run after the player's TeamColor property changed.
		connection:disconnect() -- We don't want to run it many times, only once. :P
	end
end)

I suppose that'll make it easy for you to see that you're gaining considerable size by using the wait method. It allows you to write more efficient code that looks nicer and less complex and it is deplorable how few scripters know about this.