Chapter 6. Data Structures

In the chapter, we will examine user defined data and predefined structures.

6.1. User Defined Structures

It's possible to define your own structures. A structure is a collection of variables like for example a point that consist of an x and a y coordinate:

// Define a point structure
.struct Point {x,y}

// Create a point with x=1 and y=2 and print it
.var p1 = Point(1,2)
.print ”p1.x=” + p1.x
.print ”p1.y=” + p1.y

// Create a point with the default contructor and modify its arguments
.var p2 = Point()
.eval p2.x =3
.eval p2.y =4

You define a structure with the .struct directive. The above structure has the name ‘Point’ and consists of the variables x and y. To create an instance of the structure, you use its name as a function. You can either supply no arguments or give the init values of all the variables. You use the values generated by structures as any other variables, ex:

        lda #0
        ldy #p1.y
        sta charset+(p1.x>>3)*height,y

You can get access to informations about the struct and access the fields in a more generic way by using the struct’s functions:

.struct Person{firstName,lastName}
.var p1 = Person(“Peter”,”Schmeichel”)

.print p1.getStructName()        // Prints ‘Person’ 
.print p1.getNoOfFields()        // Prints ‘2’
.print p1.getFieldNames().get(0) // Prints ‘firstName’

.eval p1.set(0,”Kasper”)         // Sets firstName to Kasper 
.print p1.get(“lastName”)        // Prints “Schmeichel”


// Copy values from one struct to another
.var p2 = Person()
.for (var i=0; i<p1.getNoOfFields(); i++) 
    .eval p2.set(i,p1.get(i))

// Print the content of a struct: 
//   firstName = Casper
//   lastName = Schmeichel
.for (var i=0; i<p1.getNoOfFields(); i++) {
    .print p1.getFieldNames().get(i) + “ = “ + p1.get(i)
}

Here is a list of the functions defined on struct values:

Table 6.1. Struct Value Functions

Functions Description
getStructName() Returns the name of the structure.
getNoOfFields() Returns the number of defined fields.
getFieldNames() Returns a list containing the field names.
get(index) Returns the field value of the field given by an integer index (0 is the first defined filed).
get(name) Returns the value of the field given by a field name string.
set(index,value) Sets the value of a field given by an integer index..
set(name,value) Sets the value of a field given by a name.