-
Notifications
You must be signed in to change notification settings - Fork 0
Queue
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.
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: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: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: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
Simply returns boolean whether or not the queue is empty.
Simply returns the size of the queue
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()
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"
Literally just ipairs.
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"
Works like table.concat
Lets once more use the queue:add example
print(queue:toString(", ")) -- prints "I, am, the, Walrus"