Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local function waitUntil(eventOrCondition, timeout)
- local timedOut = Instance.new("BindableEvent")
- local result = nil
- local eventConn
- local waiting = true
- local function fireTimedOut(bool)
- timedOut:Fire(bool)
- timedOut:Destroy()
- waiting = false
- end
- if typeof(eventOrCondition) == "RBXScriptSignal" then
- eventConn = eventOrCondition:Connect(function(...)
- eventConn:Disconnect()
- result = {...}
- fireTimedOut(false)
- end)
- elseif typeof(eventOrCondition) == 'function' then
- task.spawn(function()
- while not eventOrCondition() and waiting do
- task.wait()
- end
- if waiting then
- result = {eventOrCondition()}
- fireTimedOut(false)
- end
- end)
- else
- local funcName = debug.info(1, 'n')
- local ts = " "
- error("conditions must be wrapped in a function.\n"..ts.."Try:\n"
- ..ts.." "..funcName..
- "(function()\n"..ts.." ".."\treturn condition\n"..ts.." ".."end, timeout)")
- end
- task.delay(timeout, function()
- if typeof(eventOrCondition) == "RBXScriptSignal" and eventConn.Connected then
- eventConn:Disconnect()
- end
- fireTimedOut(true)
- end)
- return timedOut.Event:Wait(), unpack(result or {})
- end
- -- Usage (doesn't timeout)
- local condition = false
- task.delay(2, function() condition = true end)
- print("waiting...")
- local timedOut = waitUntil(function() return condition end, 5)
- print("done. timedOut =",timedOut)
- -- Usage (times out)
- condition = false
- print("waiting...")
- local timedOut = waitUntil(function() return condition end, 5)
- print("done. timedOut =",timedOut)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement