Skip to content

Instantly share code, notes, and snippets.

@glowcoil
Created January 17, 2015 21:23
Show Gist options
  • Save glowcoil/329ca01243936351c486 to your computer and use it in GitHub Desktop.
Save glowcoil/329ca01243936351c486 to your computer and use it in GitHub Desktop.
I'm going to write this with a made-up assembly language just to keep things simple. Suppose we have some registers named a, b, and c. Suppose we have a command "set" that sets a register's contents:
set a, 3
Now a holds the value 3. And we have a command "add" that adds two things together and stores the result in the first one, and "mul", which does the same thing with multiplication:
add a, 2
Now a holds the value 5.
We have a stack, which you can push things onto and pop things off of. If we do this:
push a
The stack has 5 on it. If we do this:
pop b
b now contains 5, and the stack is empty.
One more thing, we have an instruction "jump" to jump to another location in the program. I'll put labels for the memory locations of each instruction in the left margin:
0 set a, 0
1 add a, 1
2 jump 1
This program never stops, incrementing a 1 at a time forever. Now we have the tools to make things that look like functions. To call a function, you push an argument and the current instruction address onto the stack and jump to it, and for it to return, it pushes its return value onto the stack and jumps back to that address.
0 push 3 ; the return address
1 push 3 ; the argument to the function
2 jump 5 ; call the function
3 ; after the function returns we'll continue execution here
4
5 pop a ; (the start of the function) the argument is in a
6 pop b ; the return address is in b
7 mul a 2
8 push a
9 jump b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment