waitForFirstSignal

As a Roblox developer, it is currently too hard to wait for one of N events to fire without writing a horrible while loop. For instance, one may have a function that needs to wait for an event to fire, but the process behind that event may be able to cancel at any time. Such a scenario that I have come across is using Humanoid.MoveToFinished, but Humanoid.MoveToFinished can be put on indefinite hold if one just calls Humanoid:Move(Vector3.new(x, y, z)).

My proposed solution is something along the lines of a new wait function, perhaps called waitForFirstSignal. This function would accept a tuple of RbxScriptSignal instances, and yield until the first one was fired. Example:

local moveToCancelled = Instance.new("BindableEvent")

--Some more code

Humanoid:MoveTo(Vector3.new(x, y, z))
waitForFirstSignal(Humanoid.MoveToFinished, MoveToCancelled.Event)

Of course, this specific example could be fixed by having MoveToFinished fire whenever anything interrupts the MoveTo method, but I have come across other examples where this would be useful.

2 Likes

You can write a utility function for it.

function waitForFirstSignal(...)
    local bindable = Instance.new("BindableEvent")
    local signals = {}
    for _,event in pairs({...}) do
        signals[#signals+1] = event:Connect(function(...)
            bindable.Event:Fire(event, ...)
        end)
    end
    local args = {bindable.Event:Wait()}
    for i = 1, #signals do
        signals[i]:Disconnect()
    end
    return unpack(args)
end
19 Likes

Ooh. Clever.
I like it.
Thanks!

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