Skip to content

Commit

Permalink
Simplify task lib polyfill
Browse files Browse the repository at this point in the history
  • Loading branch information
gaymeowing committed Jul 27, 2024
1 parent bb1eff7 commit e509779
Showing 1 changed file with 15 additions and 17 deletions.
32 changes: 15 additions & 17 deletions libs/race/race.luau
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,22 @@
-- race
-- a function for getting the first return out of a vararg of functions

local task = (function()
local spawn = (function()
if task then
return task
return task.spawn
elseif string.find(_VERSION, "lune") then
return (require)("@lune/task")
return (require)("@lune/task").spawn
else
return table.freeze({
spawn = function<A..., R...>(thread_or_func: thread | (A...) -> R..., ...: A...): thread
if type(thread_or_func) == "thread" then
coroutine.resume(thread_or_func, ...)
return thread_or_func
else
local thread = coroutine.create(thread_or_func)
coroutine.resume(thread, ...)
return thread
end
end,
} :: any)
return function<A..., R...>(thread_or_func: thread | (A...) -> R..., ...: A...): thread
if type(thread_or_func) == "thread" then
coroutine.resume(thread_or_func, ...)
return thread_or_func
else
local thread = coroutine.create(thread_or_func)
coroutine.resume(thread, ...)
return thread
end
end
end
end)()

Expand All @@ -44,15 +42,15 @@ local function callback_handler<A..., R...>(

-- threads dont gc on their own, even if dead
table.clear(threads)
task.spawn(main_thread, unpack(results))
spawn(main_thread, unpack(results))
end

local function race<A..., R...>(callbacks: { (A...) -> R... }, ...: A...): R...
local threads = table.create(#callbacks) :: { thread }
local main_thread = coroutine.running()

for index, f in callbacks do
threads[index] = task.spawn(callback_handler, f, threads, main_thread, ...)
threads[index] = spawn(callback_handler, f, threads, main_thread, ...)
end

return coroutine.yield()
Expand Down

0 comments on commit e509779

Please sign in to comment.