Scripts/resources/[standalone]/ox_lib/imports/waitFor/shared.lua

35 lines
881 B
Lua
Raw Normal View History

2024-12-29 20:02:43 +00:00
---Yields the current thread until a non-nil value is returned by the function.
---@generic T
---@param cb fun(): T?
---@param errMessage string?
2024-12-30 10:15:34 +00:00
---@param timeout? number | false Error out after `~x` ms. Defaults to 1000, unless set to `false`.
---@return T
2024-12-29 20:02:43 +00: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
end
2024-12-30 10:15:34 +00:00
local start = timeout and GetGameTimer()
2024-12-29 20:02:43 +00:00
while value == nil do
2024-12-30 10:15:34 +00:00
Wait(0)
local elapsed = timeout and GetGameTimer() - start
2024-12-29 20:02:43 +00:00
2024-12-30 10:15:34 +00:00
if elapsed and elapsed > timeout then
return error(('%s (waited %.1fms)'):format(errMessage or 'failed to resolve callback', elapsed), 2)
2024-12-29 20:02:43 +00:00
end
value = cb()
end
return value
end
return lib.waitFor