The Stack and Functions · Lesson 19 of 30 · about 12 minutes
Stack Operations: Last In, First Out
Save values on the data stack and restore them in reverse order.
01 / Explain
Understand the idea
PUSH saves R0 on the data stack. POP removes the most recently pushed value and places it in R0. This last-in, first-out order is like a pile of plates: the newest plate is easiest to remove.
The teaching data stack is separate from the 256-byte memory grid. SP starts at 255 and decreases with saved data or call frames. The combined stack capacity is 256 entries; POP on an empty data stack is an error.
02 / Try
Watch it happen
Expect 22 then 11. Watch the stack return to empty and SP return to 255.
LOAD 11
PUSH
LOAD 22
PUSH
POP
PRINT
POP
PRINT
HALTUse Step to follow one instruction at a time. You can change the example and replay it.
03 / Challenge
Make it work
Read two integers, save both on the data stack, then print them in reverse order. Use PUSH and POP rather than hardcoded values.
The checker runs your current editor program in a fresh machine for each of 3 test cases. It supplies inputs and seeded memory itself; the lab’s current output and memory do not decide your result.
INPUT
PUSH
INPUT
PUSH
# Pop and print twice.
HALTNeed a hint?
Each POP changes R0, so print before popping the next value.
Reveal a worked solution
Read the program, predict each instruction’s effect, then step through it in the lab.
INPUT
PUSH
INPUT
PUSH
POP
PRINT
POP
PRINT
HALTEmoji CPU lab
Emoji program
Type LOAD, ADD, or another opcode then Space to insert emoji. Ctrl/⌘ + Enter runs or pauses; Escape pauses; Ctrl/⌘ + ] indents. Tab moves focus. Labels use a colon. Jumps use zero-based instruction addresses.
Instruction map and breakpoints (0)
Breakpoints stop before an instruction. Run resumes past the stopped breakpoint once; Step executes it directly. Editing source clears old breakpoints and machine state.
CPU registers
- R0
- 0
- R1
- 0
- R2
- 0
- R3
- 0
- R4
- 0
- R5
- 0
- R6
- 0
- R7
- 0
Stacks and loop frames
SP = 255 − data depth − call depth. The stack is separate from memory.
Data stack (bottom → top)
Empty
Call return addresses (bottom → top)
Empty
Loop frames
Empty
Output and input
Run a PRINT instruction to see output.
Queued input: Empty
Memory · 256 bytes · 0 nonzero
Each cell shows address:value. R = read this step; W = written this step. Select a cell to inspect or initialize it before execution. Use arrow keys to move, Home/End for the row, and Ctrl/⌘ + Home/End for the whole memory.
Execution trace · 0 entries
Recent entries below. Inspect any zero-based index to see complete detached before/after state.
Check your challenge
You can run this check any time. Every case must pass to record completion.
Progress uses localStorage only. It stays on this browser and is never sent to a server.