Skip to content

Instantly share code, notes, and snippets.

@bytejon
Last active January 8, 2026 21:33
Show Gist options
  • Select an option

  • Save bytejon/fbed7b62ceec337afb48a1622d4c1fde to your computer and use it in GitHub Desktop.

Select an option

Save bytejon/fbed7b62ceec337afb48a1622d4c1fde to your computer and use it in GitHub Desktop.
Luau utility for general purpose thread reuse with a more efficient approach than standard. This can be made more efficient if applied to specific domains, like signaling.
-- jonbyte, 2026
local queue = {} :: array<{
fn: callback,
args: argpack
}>
local active = false
local index = 1
local epoch = 0
local thread: thread?
local function exec(
e: number
)
thread = nil
while index <= #queue do
local entry = queue[index]
local fn = entry.fn
local args = entry.args
local last = index
fn(table.unpack(args, 1, args.n))
if not (e == epoch and index == last) then
return
end
index += 1
end
thread = coroutine.running()
end
local function main()
while true do
exec(coroutine.yield())
end
end
local function run(
fn: callback,
...: any
)
table.insert(queue, {
fn = fn,
args = table.pack(...)
})
if active then
return
end
active = true
while index <= #queue do
thread = thread or task.spawn(main)
task.spawn(thread, epoch)
if index <= #queue then
index += 1
end
end
table.clear(queue)
index = 1
epoch += 1
active = false
end
type array<V> = { V }
type callback = (...any) -> ()
type argpack = { n: number, [number]: any }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment