Advertisement
Mangus875

[NEW!] Roblox: Wait For Condition or Event w/ Timeout

Apr 19th, 2023 (edited)
1,362
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.56 KB | Help | 0 0
  1. local function waitUntil(eventOrCondition, timeout)
  2.     local timedOut = Instance.new("BindableEvent")
  3.     local result = nil
  4.  
  5.     local eventConn
  6.     local waiting = true
  7.     local function fireTimedOut(bool)
  8.         timedOut:Fire(bool)
  9.         timedOut:Destroy()
  10.         waiting = false
  11.     end
  12.  
  13.     if typeof(eventOrCondition) == "RBXScriptSignal" then
  14.         eventConn = eventOrCondition:Connect(function(...)
  15.             eventConn:Disconnect()
  16.             result = {...}
  17.             fireTimedOut(false)
  18.         end)
  19.     elseif typeof(eventOrCondition) == 'function' then
  20.         task.spawn(function()
  21.             while not eventOrCondition() and waiting do
  22.                 task.wait()
  23.             end
  24.             if waiting then
  25.                 result = {eventOrCondition()}
  26.                 fireTimedOut(false)
  27.             end
  28.         end)
  29.     else
  30.         local funcName = debug.info(1, 'n')
  31.         local ts = "                "
  32.         error("conditions must be wrapped in a function.\n"..ts.."Try:\n"
  33.             ..ts.."  "..funcName..
  34.             "(function()\n"..ts.."  ".."\treturn condition\n"..ts.."  ".."end, timeout)")
  35.     end
  36.  
  37.     task.delay(timeout, function()
  38.         if typeof(eventOrCondition) == "RBXScriptSignal" and eventConn.Connected then
  39.             eventConn:Disconnect()
  40.         end
  41.         fireTimedOut(true)
  42.     end)
  43.  
  44.     return timedOut.Event:Wait(), unpack(result or {})
  45. end
  46.  
  47. -- Usage (doesn't timeout)
  48. local condition = false
  49. task.delay(2, function() condition = true end)
  50. print("waiting...")
  51. local timedOut = waitUntil(function() return condition end, 5)
  52. print("done. timedOut =",timedOut)
  53.  
  54. -- Usage (times out)
  55. condition = false
  56. print("waiting...")
  57. local timedOut = waitUntil(function() return condition end, 5)
  58. print("done. timedOut =",timedOut)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement