Files
ox_lib/imports/waitFor/shared.lua

35 lines
881 B
Lua
Raw Normal View History

---Yields the current thread until a non-nil value is returned by the function.
2023-07-31 16:06:44 +10:00
---@generic T
---@param cb fun(): T?
2023-07-31 16:06:44 +10:00
---@param errMessage string?
2024-02-02 13:45:01 +11:00
---@param timeout? number | false Error out after `~x` ms. Defaults to 1000, unless set to `false`.
---@return T
2023-07-31 16:06:44 +10:00
---@async
function lib.waitFor(cb, errMessage, timeout)
local value = cb()
if value ~= nil then return value end
if timeout or timeout == nil then
if type(timeout) ~= 'number' then timeout = 1000 end
2023-07-31 16:06:44 +10:00
end
local start = timeout and GetGameTimer()
2023-07-31 16:06:44 +10:00
while value == nil do
Wait(0)
local elapsed = timeout and GetGameTimer() - start
2023-07-31 16:06:44 +10:00
if elapsed and elapsed > timeout then
return error(('%s (waited %.1fms)'):format(errMessage or 'failed to resolve callback', elapsed), 2)
2023-07-31 16:06:44 +10:00
end
value = cb()
end
return value
end
return lib.waitFor