From 39db64000ebddc023364785e9a7e85e05d16bcaa Mon Sep 17 00:00:00 2001 From: Christoph Date: Sun, 5 Oct 2025 21:42:53 +0200 Subject: [PATCH] Fix Stack:Peek() bug + check for empty stack if appropriate --- lib/stack.lua | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/lib/stack.lua b/lib/stack.lua index adaf245..88cebc1 100644 --- a/lib/stack.lua +++ b/lib/stack.lua @@ -1,5 +1,7 @@ +local Position = require("lib.position") + ---@class Stack ----@field elements table[] +---@field elements Position[] local Stack = {} Stack.__index = Stack @@ -17,9 +19,10 @@ function Stack:Create() end ----@param element table +---@param element Position function Stack:Push(element) if element == nil or element == {} then + printError("Failed to push empty element to the stack!") return end @@ -27,15 +30,25 @@ function Stack:Push(element) end ----@return table +---@return Position | nil function Stack:Pop() + if self:Count() == 0 then + printError("Failed to pop element from the empty stack!") + return nil + end + return table.remove(self.elements) end ----@return table +---@return Position | nil function Stack:Peek() - return table[#self.elements] + if self:Count() == 0 then + printError("Failed to peek element from the empty stack!") + return nil + end + + return self.elements[#self.elements] end