Files

43 lines
1.1 KiB
Lua
Raw Permalink Normal View History

--[[
https://github.com/overextended/ox_lib
This file is licensed under LGPL-3.0 or higher <https://www.gnu.org/licenses/lgpl-3.0.en.html>
2025-03-29 21:44:03 +11:00
Copyright © 2025 Linden <https://github.com/thelindat>
]]
---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