Fix Stack:Peek() bug + check for empty stack if appropriate
This commit is contained in:
@ -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
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user