Utilities
Data structures
Queue, Stack, Set, PriorityQueue, LRU and RingBuffer.
Create each with .new(...) and call methods with a colon.
Queue
First in, first out.
| Method | Meaning |
|---|---|
Queue.new() | Creates an empty queue |
q:push(value) | Adds to the back |
q:pop() | Removes and returns the front, or nil |
q:peek() | Returns the front without removing it |
q:size() | Number of items |
q:clear() | Empties it |
Stack
Last in, first out. Same methods as Queue: push, pop (takes from the top), peek, size, clear.
Set
A collection without duplicates.
| Method | Meaning |
|---|---|
Set.new(list) | Creates a set, optionally from an array |
s:add(value) | Adds a value. Returns the set |
s:remove(value) | Removes a value. Returns the set |
s:has(value) | true if present |
s:size() | Number of values |
s:items() | Array of the values |
s:union(other) | New set with everything from both |
s:intersect(other) | New set with what is in both |
PriorityQueue
Always gives you the item with the lowest priority number first.
| Method | Meaning |
|---|---|
PriorityQueue.new() | Creates an empty queue |
q:push(value, priority) | Adds an item |
q:pop() | Removes and returns value, priority of the lowest, or nil |
q:size() | Number of items |
local q = PriorityQueue.new()
q:push("far", 30)
q:push("near", 5)
print(q:pop()) -- near 5
LRU
A cache that forgets the least recently used entry when it is full.
| Method | Meaning |
|---|---|
LRU.new(capacity = 64) | Creates a cache |
c:get(key) | Returns the value and marks it as recently used, or nil |
c:set(key, value) | Stores a value, removing the oldest if the cache is full |
RingBuffer
Keeps the latest capacity values.
| Method | Meaning |
|---|---|
RingBuffer.new(capacity = 32) | Creates a buffer |
r:push(value) | Adds a value, overwriting the oldest when full |
r:toarray() | Returns the values from oldest to newest |
r:size() | Number of values stored |