8th Tutorial

Lession 8: More data types in 8th

Note: if you haven’t yet installed 8th, please do so right now and follow the installation instructions as presented in the manual!

Container types

A “container” type is one which can hold other data types. You’ve already seen one such type, the “variable”. A variable is a container which can hold just one item at a time. While useful, you will probably need more sophisticated containers. 8th provides quite a few for your use, and all of them may contain any of 8th’s data types:

  • array — a container which accesses its contents by numeric index. So you can get the first item, the tenth item, etc. An array grows as large as needed. The first item is at index 0.
  • map — a container which accesses its contents by string index. So you can get the item corresponding to "one" if there is a key by that name. Like an array, a map grows as large as needed
  • stack — a container which accesses its contents using “pop” and “push”. You’re already familiar with the “data stack”. 8th lets you create however many additional stacks you desire. A stack has a fixed size, determined when it is created
  • heap — a container which keeps its contents in a sorted order. You determine that order by giving the heap a word to use for comparison purposes when you create the heap. A heap can grow as needed.
There are a number of other container types, please read the manual for all the details.

To declare an array, you simply use JSON syntax:

[ 1, 2, 3]
Similarly with a map:
{ "one" : 1, "two" : 2}
You can access an array’s values using a:@ and a:!, and likewise a map with m:@ and m:!

I/O types

8th provides several namespaces with associated data types which deal with input-output:

  • f — read/write etc disk-based files
  • net — network/socket I/O
  • db — SQLite or MySQL database I/O
  • sio — serial I/O
There are others as well. T

Exercises

Try the following:

  • Create an array containing the items “1”, “5” and “10”
  • Get the item at index #1 (e.g. the second item, “5”). Look at the stack — what do you notice?
  • Push the “5” onto the stack again using a:push. Look at the stack and see what the array looks like now.
  • Read the documentation for a:each and write a line of code which will print each item in the array on a separate line
  • Read the documentation for f:create and f:write and f:close
  • Create a new file “test.txt” which contains the text “hello, world”

Conclusion

You’ve been given a taste of the rich variety of 8th’s data types. One more lesson beckons: conditionals and loops