Skip to content

Commit

Permalink
TaskQueue types
Browse files Browse the repository at this point in the history
  • Loading branch information
Sleitnick committed Oct 17, 2023
1 parent d1a742e commit 8c67a59
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 14 deletions.
27 changes: 27 additions & 0 deletions modules/task-queue/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
declare namespace TaskQueue {
interface Constructor {
new <T>(onFlush: (items: T[]) => void): TaskQueue<T>;
}
}

interface TaskQueue<T> {
/**
* Add an item to the queue.
*/
Add(item: T): void;

/**
* Clears items in the queue (except for items currently being flushed,
* which would only occur if the flushing function yielded).
*/
Clear(): void;

/**
* Alias for `Clear()`.
*/
Destroy(): void;
}

declare const TaskQueue: TaskQueue.Constructor;

export = TaskQueue;
28 changes: 15 additions & 13 deletions modules/task-queue/init.lua
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
--!strict

-- TaskQueue
-- Stephen Leitnick
-- November 20, 2021
Expand Down Expand Up @@ -32,16 +30,18 @@ local TaskQueue = {}
TaskQueue.__index = TaskQueue

--[=[
@param onFlush ({T}) -> nil
@param onFlush ({T}) -> ()
@return TaskQueue<T>
Constructs a new TaskQueue.
]=]
function TaskQueue.new<T>(onFlush: ({ T }) -> nil)
function TaskQueue.new<T>(onFlush: ({ T }) -> ())
local self = setmetatable({}, TaskQueue)

self._queue = {}
self._flushing = false
self._flushingScheduled = false
self._scheduled = nil
self._onFlush = onFlush

return self
end

Expand All @@ -51,17 +51,14 @@ end
]=]
function TaskQueue:Add<T>(object: T)
table.insert(self._queue, object)
if not self._flushingScheduled then
self._flushingScheduled = true
task.defer(function()
if not self._flushingScheduled then
return
end

if self._scheduled == nil then
self._scheduled = task.defer(function()
self._flushing = true
self._onFlush(self._queue)
table.clear(self._queue)
self._flushing = false
self._flushingScheduled = false
self._scheduled = nil
end)
end
end
Expand All @@ -81,8 +78,13 @@ function TaskQueue:Clear()
if self._flushing then
return
end

if self._scheduled ~= nil then
task.cancel(self._scheduled)
self._scheduled = nil
end

table.clear(self._queue)
self._flushingScheduled = false
end

--[=[
Expand Down
2 changes: 1 addition & 1 deletion modules/task-queue/wally.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "sleitnick/task-queue"
description = "Batches tasks that occur on the same execution step"
version = "0.1.1"
version = "1.0.0"
license = "MIT"
authors = ["Stephen Leitnick"]
registry = "https://github.com/UpliftGames/wally-index"
Expand Down

0 comments on commit 8c67a59

Please sign in to comment.