Skip to content
JJSax edited this page May 19, 2023 · 1 revision

Queue Library

Why and When to use

A queue data structure is typically used when you need to manage elements in a first-in, first-out (FIFO) order. It is useful in scenarios where you want to process elements in the order they were added, such as handling tasks in a sequential manner, managing a message queue, or implementing breadth-first search algorithms.

Usage

There are two ways to create a queue.

The Tablua Generic method Directly from queue.lua

-- Option 1) From Tablua
local Tablua = require "Tablua"
local myQueue = Tablua.Queue() -- This is the exact same as option 2

-- Option 2) From queue.lua
local Queue = require "Tablua.queue"
local myQueue = Queue.new()

All below expect option 1 has already been done.

queue:enqueue

queue:add is exactly the same as queue:enqueue

adds contents to the end of the queue.

myQueue:enqueue("I")
myQueue:enqueue("am")
myQueue:add("the")
myQueue:add("Walrus")

queue:dequeue

queue:remove is exactly the same as queue:dequeue

Takes the first item in the queue, takes it out of the queue and returns the value.

Lets use what we made in the queue:add example.

for i = 1, 4 do
    print(myQueue:dequeue()) -- will print "I" then "am" then "the" then "Walrus"
end

queue:peek

queue:front is exactly the same as queue:peek

Lets you see what the first item in the queue is, without removing it.

Lets again start with the example we made in the queue:add example.

for i = 1, 4 do
    print(myQueue:peek()) -- will print "I" 4 separate times since "I" never gets removed.
end

queue:isEmpty

Simply returns boolean whether or not the queue is empty.

queue:getSize

Simply returns the size of the queue

queue:clear()

Cleared the contents of the queue. This is not the same as creating a new queue. If you absolutely need to keep the same memory address, then use this function. Otherwise it will be more efficient to just do this.

myQueue = Tablua.Queue()

queue:contains

Returns if the queue contains a value and where it is in the queue.

myQueue:add(1)
myQueue:add("hi")
myQueue:add(3)

print(myQueue:contains(2)) -- prints "hi 2"

queue:iterate

Literally just ipairs.

queue:clone

Clones the queue into a new queue with a different memory address

myQueue:add("hello")
myQueue:add("world")

queue2 = myQueue:clone()
myQueue:dequeue() -- removes "hello" from myQueue

print(queue2:dequeue()) -- prints "hello" even after removed from myQueue
print(queue2:dequeue()) -- prints "world"

queue:toString

Works like table.concat

Lets once more use the queue:add example

print(queue:toString(", ")) -- prints "I, am, the, Walrus"
Clone this wiki locally