It looks like you're new here. If you want to get involved, click one of these buttons!
--[[ stack.lua This Lua class implementation of a stack data structure was based on Mário Kašuba's function in the book, Lua Game Development Cookbook (2015) ]] Stack = Core.class() function Stack:init(list) if not list then -- create an empty stack self.stack = {} else -- initialise the stack self.stack = list end end function Stack:push(item) -- put an item on the stack self.stack[#self.stack+1] = item end function Stack:pop() -- make sure there's something to pop off the stack if #self.stack > 0 then -- remove item (pop) from stack and return item return table.remove(self.stack, #self.stack) end end function Stack:iterator() -- wrap the pop method in a function return function() -- call pop to iterate through all items on a stack return self:pop() end end |
-- main.lua local stack = Stack.new({"one","two", "three", "four", "five"}) stack:push("six") stack:push("seven") print ("Remove an item from the stack: "..stack:pop()) for item in stack:iterator() do print("Item: ".. item) end |
Likes: SinisterSoft, hgy29, antix, n1cke, Apollo14
Comments
https://deluxepixel.com
You can check it with something like `print(stack1.pop == stack2.pop)`.
You need to put all Stack functions outside `function Stack:init(list)`, for example:
table.insert for push
and
x=t[#t] t[#t]=nil for pop
wouldn't be good enough?
Fragmenter - animated loop machine and IKONOMIKON - the memory game
table.insert and table.remove does it.
Fragmenter - animated loop machine and IKONOMIKON - the memory game
The main purpose of this tutorial was to demonstrate some fundamental data structures for game programming using OOP. Speed is crucial for a lot of games, I know, so where ever performance improvements can be made all the better!!
Likes: antix, n1cke