burge91 wrote
I'm mainly concerned about what I should be doing with the stack pointer. Since memory is all zero to start with, when I test my programs the stack pointer points to zero, which causes the program to fail. (I don't know if I'm just confused here or whether my question makes sense? In the past I have come here asking questions that don't make sense, could be a psychological made up roadblock).
To answer your questions. It would overwrite -418 with 42, then point to ram[305].
ASM instructions I imagine are:
@SP
A=M
@42
M=A
@SP
M=M+1
Is this correct?
Well, let's kill a (virtual) tree and find out.
At the beginning of your code segment, we don't know what's in A or D, so we will use question marks for those:
// D = ?
// A = ?
// RAM[0] = 304
// RAM[304] = -418
@SP
// A = 0
A=M
// A = 304
@42
// A = 42
M=A
// RAM[42] = 42
@SP
// A = 0
M=M+1
// RAM[0] = 305
Does this do what you want it to?
If not, do you see where the problem is?
My add program doesn't quite work I think because of my stack issue.
How are you testing things? Are you just running it, or are you using the test script?
Look at the test script:
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/07/StackArithmetic/SimpleAdd/SimpleAdd.tst
load SimpleAdd.asm,
output-file SimpleAdd.out,
compare-to SimpleAdd.cmp,
output-list RAM[0]%D2.6.2 RAM[256]%D2.6.2;
set RAM[0] 256, // initializes the stack pointer
repeat 60 { // enough cycles to complete the execution
ticktock;
}
output; // the stack pointer and the stack base
The first thing it does (after setting up the file and output parameters) is to force the SP to point to 256.
This is because, as explained in the text, the first few test scripts perform stack initialization for you because you haven't gotten to the implementation of the bootstrap code yet.
So if you are just running your code without a test script, you are responsible for making sure that the SP gets properly initialized.