A struct type is declared using a labeled
DATA
block. The label is in the format
@STRUCT_NAME
where
NAME
is the name of the struct; e.g. if you’re creating a complex number struct you might write
@STRUCT_COMPLEX
.
The structure of the
DATA
block consists of strings in type-name pairs. The end of the definition is notated as
DATA "END"
.
To continue with our complex number example:
@STRUCT_COMPLEX
DATA "FLOAT","REAL"
DATA "FLOAT","IMAGINARY"
DATA "END"
Here, each line is a field declaration. This defines a struct with two floating-point fields: one named
REAL
and one named
IMAGINARY
. The valid type indicators are
INT
for integers,
FLOAT
for doubles, and
STRING
for strings.
Now that a valid struct has been defined, we can create a variable based on it. The process is simple:
DIM CPX[0]
STRUCT "COMPLEX" OUT CPX
The bare (that is, zero length with no type suffix) array
CPX
contains the data representing a
COMPLEX
struct. Now it can be treated and manipluated as a struct using the library. More specifically, it contains the
struct type
(
COMPLEX
) and data representing all
fields
(
REAL
,
IMAGINARY
.) This struct is based on the data specified at
@STRUCT_COMPLEX
. When first created, all fields specify their default value according to type; for
INT
it is 0, for
FLOAT
it is 0.0, and for
STRING
it is the empty string.
The method of manipulating fields is rather simple. To set a field’s value, we use
SET
.
SET CPX,"REAL",1
Here the field
REAL
(specified as a string in the second argument) in
CPX
is set to 1. The same can be done for all fields and all types of fields without fail. Be wary, however, because due to the lack of proper error handling in SmileBASIC,
trying to set a field that doesn’t exist within the struct fails silently.
Getting the value of a field is just as easy. The
FIELD
function is used to return that field’s value.
PRINT FIELD(CPX,"REAL")
Here the value of the field
REAL
in
CPX
is obtained and printed. As with
SET
, this function lacks proper error handling.
A nonexistent field will
always
return 0, regardless of expected type.
To avoid error conditions, the programmer should check struct types for validity when necessary. The main way of doing this is the
INSTANCEOF
function.
INSTANCEOF(STRUCT,"TYPE")
This returns true if
STRUCT
is an instance of the struct
TYPE
, otherwise false. This test checks both against the struct’s internal type and its
signature
(the name and type of its fields.) If these do not match up
exactly
with a defined struct type then the check is guaranteed false. Improper tampering of the struct’s internal data may cause this check to fail when it otherwise would be guaranteed to pass.
A struct can be converted to (and then parsed back out of) a single string. This can be used to keep a collection of structs inside a plain string array, or save a struct to a text file.