Created
July 21, 2025 03:39
-
-
Save magicoal-nerb/89e600088460803e30b01d1930da9e7f to your computer and use it in GitHub Desktop.
stack in luajit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Stack.lua | |
-- Last in, first out | |
-- poopbarrel/magicoal_nerb :^) | |
local Stack = {} | |
Stack.__index = Stack; | |
function Stack.new(capacityPow) | |
local mask = bit.lshift(1, capacityPow) - 1 | |
-- create an array beforehand so lua doesn't | |
-- need to rehash it | |
local arr = table.new(mask + 1, 0) | |
return setmetatable({ | |
mask = mask, | |
ptr = 0, | |
count = 0, | |
arr = arr, | |
}, Stack); | |
end | |
function Stack:clear() | |
self.count = 0 | |
self.ptr = 0 | |
end | |
function Stack:getCount() | |
return self.count | |
end | |
function Stack:iterate(fn) | |
local raw = self.ptr - 1 | |
local arr = self.arr | |
for i = 0, self.count - 1 do | |
local ptr = bit.band(raw - i, self.mask) + 1 | |
fn(arr[ptr]) | |
end | |
end | |
function Stack:peek() | |
return self.arr[self.ptr] | |
end | |
function Stack:push(value) | |
self.ptr = bit.band(self.ptr, self.mask) + 1 | |
self.count = self.count + 1 | |
self.arr[self.ptr] = value | |
end | |
function Stack:empty() | |
return self.count == 0 | |
end | |
function Stack:pop() | |
local object = self.arr[self.ptr] | |
self.ptr = bit.band(self.ptr - 2, self.mask) + 1 | |
self.count = self.count - 1 | |
assert(self.count < self.mask, "Wtf") | |
return object | |
end | |
return Stack; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment