Page 1 of 1

Stage 119-124: Records, Tables and Structures

Posted: Sun Jul 23, 2023 9:24 am
by frank
During the previous stage, full support for records was implemented. See the documentation. From a compiler perspective, records are also at the base of structures and tables.

Structures or user-defined types (UDT's) are well-known in many programming languages and during this stage, support for structures has been revised (see stages 94-95). While at it, a table type was also added. Think of tables as an in-between type: they are more flexible than records, more limited than structures with regards to field type support, but with one major advantage: their fields can be referenced by index, which gives them kind of enumeration functionality:

Code: Select all

table ttest is
  id      : int;
  title   : str;
  buffer  : byte * 16;
  last    : bool;
end

decl sub table_test();

main do
  table_test();
end

sub table_test()
  dim test: ttest;
  dim i: itr;
do
  with test do
    .id = 1;
    print(.id);
    .title = "This is a table.";
    print(.title);
    ' fld() returns a table field's index
    for i = 0 to fld(.last) :++ do
      if i == fld(.title) do
        print("title is field #:");
      end
      print(i+1);
    end
  end
end
The function fld() can only be used in conjunction with table fields as it returns a field's index. With fields grouped in a specific order, they can be acted upon by their index. For instance, it is possible to iterate through a group of strings like fld(.string_1) to fld(.string_n). Note that the last field was referenced by fld(.last), whatever the name of the last field is. This can also be accomplished by upp(test), since table fields are like array elements.

It is also possible to define a table of constants:

Code: Select all

const table messages is
  msg1 = "first message";
  msg2 = "second message";
  msg3 = "third message";
end

dim msg: messages;
dim num: uint;

main do
  num = 2;
  ' by message number (zero-based)
  print(msg[num]);
  ' by message name
  print(msg.msg3);
end
This can be particularly useful for referencing (large) tables of fixed data, such as error messages.

To be continued...