Using field variables are not compiling

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Using field variables are not compiling

peterxu422
I'm trying to compile a .jack file with JackCompiler.bat, but I'm getting compile errors when I am using a field variable in one of the class's functions.

For instance, in the class below:

class Array {
       
        field (Array/int) base;      //tried using Array and int as type
       
    function Array new(int size) {
                let base = ....        //line 16
                return base;          //line 17
    }

    method void dispose() {
                do functionName(base);
                return;
    }
}

When I try to compile this with JackCompiler.bat, I get the following errors:

In Array.jack (line 16): In subroutine new: base is not defined as a field, parameter or local or static variable
In Array.jack (line 17): In subroutine new: base is not defined as a field, parameter or local or static variable

I don't understand the errors. It don't see what's wrong with the way I declared base.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Using field variables are not compiling

cadet1620
Administrator
The error message is a bit misleading. The problem is that functions do not have this pointers so they cannot access field variables; they can only access static class variable.

You may also be confusing the compiler by using Array as the class you are defining and as the type of a field variable.

Here's a quick example of the three types of subroutines that can be defined in a class:
class MyArray {
       
    field Array base;           // One base for every instance of MyArray
    static Array default_base;  // All constructor/method/function share a
                                // single copy of default_base
       
    // *constructor*
    // Must return the same type as the class.
    // Must return "this"
    // Has a "this" pointer so it can access fields.
    constructor MyArray new(int size) {
        let base = Array.new(123);
        return this;
    }

    // *method*
    // May return any type including void.
    // Has a "this" pointer so it can access fields.
    method void dispose() {
        do base.dispose();
        return;
    }
    
    method Array newAgain(int size) {
        do base.dispose();
        let base = Array.new(123);
        return base;
    }

    // *function*
    // May return any type including void.
    // Does not have a "this" pointer so it can only access statics.
    function Array getDefault(int size) {
        return default_base;
    }    
}

--Mark
Loading...