Stacks

A stack is a linear data structure with a collection of items that follows the Last-In-First-Out (LIFO) principle. You can think of it as a stack of dinner plates: you start with one, and then you put another above it. When you take plates from the stack, the first one you remove from the stack is the last one you put on the top.

In programming, adding an item to a stack, like putting a plate on the top of a stack, is called pushing; removing an item from the stack, like taking away the plate on the top of a stack, is called popping.

Implementing Stacks

Luau doesn't have stacks as a built-in data structure, but you can use tables to implement stacks. The following code sample shows how to create a stack, push an object to a stack, and pop an object from the stack.


1-- OOP boilerplate - create a class, add __index, then make a constructor
2Stack = {}
3Stack.__index = Stack
4function Stack.new() return setmetatable({}, Stack) end
5
6-- Put a new object onto a stack
7function Stack:push(input)
8 self[#self+1] = input
9end
10-- Take an object off a stack
11function Stack:pop()
12 assert(#self \> 0, "Stack underflow")
13 local output = self[#self]
14 self[#self] = nil
15 return output
16end
17

You can add the following code sample and change the items you push or pop from the stack to test it out:


1-- Note: Don't forget to copy/paste the code from above
2-- Make a new stack
3local s = Stack.new()
4
5-- Do stuff Resulting stack
6s:push(1) -- {1}
7s:push(5) -- {1, 5}
8s:push(10) -- {1, 5, 10}
9print(s:pop()) -- {1, 5}
10print(s:pop()) -- {1}
11s:push(20) -- {1, 20}
12print(s:pop()) -- {1}
13print(s:pop()) -- {}
14

If you run the previous code sample without changing anything, the expected output is:


110
25
320
41
5