15 April 2016

Lesson 17 – Using files in 8th – Part 2


Reading a file in one sweep

Sometimes it is useful to read a file into memory in one go. For that we have the word f:slurp.
This word creates a buffer instead of a string! This means that is not the best way for reading a text file, if only because it can consume lots of memory. For a text file we’d better use f:eachline as in this example:



OS level file write operations invoked by 8th


f:chmod
Most often used to change the read-only mode of the file; on Unix-like OSes can do many more things.

f:copy
Tries to copy a file.

f:copydir
Tries to (recursively) copy a whole directory.

f:link
Tries to create a symbolic link to a file. This feature is mostly used in Unix like OS-es.

f:mkdir
Tries to create a new directory.

OS level file info requests

f:canwrite?
Detects if it is possible to write to a given file.

f:ctime
Gets creation time of a file.

Read the manual

When I go through the manual for the f namespace I see a lot of very useful words.
So really, you should study the manual, otherwise you’ll miss the juicy parts of 8th

A final example of file handling

We will:
1. Go into the root directory c:\ (Windows here)
2. Check if a directory with the name example already exists there
3. If not, create it
4. Go into that directory
5. Create a small text file there
6. Query some file info of that file

Program source code


"example"  var, dirName
"test.txt" var, fileName
false      var, dirExists
["line 1\n", "line 2\n", "line 3\n"] var, records

: chkSubdir
  dirName @ f:exists?
  if 
    "The name already exists and ..." . cr
    dirName @ f:dir?
    if 
      true dirExists !
      "... it is indeed a directory!" . cr
    else
      "Error: a file with that name exists already!"
      . cr reset bye
    then
  else
    "The directory does not exist yet ..." . cr
  then
  ;

: makeDir
  dirExists @ not
  if
    "... so we create it now!" . cr
    dirName @ f:mkdir not
    if 
      "Error: cannot create directory!" . 
      cr reset bye 
    then
  then
  ;

: openFile
  fileName @ f:create dup   \ dup to retain file handle
  null? 
  if 
    "Error: error while creating file!" . 
    cr reset bye 
  then
  ;

: helpWrite
          \ Stack: file ix value   
  swap    \ Stack: file value ix
  drop    \ Stack: file value
  f:write \ Stack: file rc
  null? if "Error: writing to file!" . cr reset bye then
          \ Stack: file
  ;
  
: writeFile
  records @ ' helpWrite a:each 
  drop \ Get rid of array now
  ;

: openro
  fileName @ f:open-ro
  dup null? \ dup to retain file handle
  if
    "Error: error while reopening file!" . cr reset bye
  then
  ;
  
: queryFile
  getcwd "Current directory is: " . . cr
  fileName @ f:exists?
  if
    "The file does indeed exist now!" . cr
  else
    "Error: file not found!" . cr reset bye
  then
  openro
  f:size  "File size       : " . . " bytes" . cr
  f:ctime "File created at : " . . cr
  f:mtime "File modified at: " . . cr
  f:close
  ;
  
: app:main
  "c:\\" chdir     \ Set current directory to c:\
  chkSubdir        \ Does the subdirectory exist?
  makeDir          \ If not, create it!
  dirName @ chdir  \ Set current directory 
  openFile         \ Open a file for output
  writeFile        \ Write the records to the file
  f:close          \ Close the output file
  openro           \ Open written file for read
  queryFile        \ Now query some file specs
  bye
  ;
  

Below the output of two consecutive runs:



More info about 8th


8th Website:   http://8th-dev.com
8th Forum:   http://8th-dev.com/forum
My YouTube Channel:   https://goo.gl/DscYVD
The Big 8th Lessons Book:   http://goo.gl/qDa6fH

11 March 2016

Lesson 16 – Using files in 8th – Part 1

Input and output

In order to permanently store data, we need a system to provide that possibility. Every full blown Operating System has got it’s own filesystem(s). E.g. in modern Windows you can use the NTFS file system and in Linux the ext2, ext3 and even Reiserfs file systems.

The file system is a layer between the OS and the hardware. The OS provides specific interfaces (API’s) for programmers to use such a file system.

Most programming languages encapsulate these API’s in their own programming language parlance.

Today we will start to learn how 8th does this.

It is very important to note that 8th is a Multi Platform development tool and that the file handling we do as a developer is on an abstract high level in such a way that 8th behaves correct even when using totally different file systems on totally different OS-es!

What is a file?

A file is a collection of sequentially stored records.

Mostly files are written and read sequentially (record by record). However, it is possible to point to a specific part of a file and read / write “at random”.

Furthermore, there is an important difference between 2 types of file:

  • Text files - such files are written line by line. Each line ends with (a combination of) CR (Carriage Return) and/or LF (Line Feed) characters (sometimes called newline characters
    • Example:   documents
  • Binary files - these files can contain anything. CR and LF characters that happen to be part of such a file have no special meaning
    • Example:   executable files, pictures (JPG), music (MP3), etc.

Files are also used as the building blocks of a database. But that is out of scope for us today.

Test if a given file does exist

If you are not sure if a file does exist, you can check for that:






If false is returned, the file does not exist (as in this case), otherwise true

Create a new file

Before we can write to a file, we must create that file, like so:


If the operation fails, the item on the stack will be null, otherwise it will be the file handle of the file just created.

Write to the new file

As we can see in the previous picture, f:create leaves the file handle on the stack, which is convenient for writing, because f:write expects that file handle to be on the stack!

Writing a line goes like so:



As we see on the stack there are now 2 items:

  • at TOS is the number of bytes written (here: 6) or null if the operation failed
  • at position 2 there is still the file handle (which is convenient for other writes)

Do not forget to check for null!

For now we drop the value on TOS:



As we can see the file handle is now at TOS again.

Now we write a second line:



As we can see the operation succeeded again and the file handle is still present in position 2 on the stack.

We drop the result again:



and see that the file handle is still present.

Close the file just written

In order to make the file correctly visible and complete in the file system of the OS, we must close the file:







The close word grabs the file handle from TOS and closes the file.

Maybe you would expect a return code from the close word. However, that would be meaningless, because we cannot “recover” anything if it failed!

Checking the file which we wrote

Using a text editor we now open the file just created:












We see that there is just one line written, with the text of both write operations. What the heck??? I wanted to write 2 text records, not this!!!

Binary file by default

In 8th by default files are written as binary files.

In our examples we didn’t provide a newline (CR of LF) character, which is needed in text files!

How to write a text file?

Well, that is easy! You should append a newline to your text to be written. Instead of:

  • “line 1”    f:write

You should use:

  • “line 1\n”    f:write

More info about 8th

8th Website:   http://8th-dev.com
8th Forum:   http://8th-dev.com/forum
My YouTube Channel:   https://www.youtube.com/channel/UCcwRyVDxU-lMfWgz_10DudA
The Big 8th Lessons Book:   http://goo.gl/qDa6fH

07 February 2016

Lesson 15 – Using maps in 8th

Conclusion of the lessons on arrays

In the previous lessons we have seen the most advanced words for the array namespace.

Now it is time for you to discover for yourself the other words in that namespace. Learning a language is best done using it. So please play with these words!

What is a map in 8th?

A map is a collection of key / value pairs. The keys are unique within a map. Instead of referencing an item by index (like with arrays) you must reference an item by key.

Keys must be strings in 8th. Values can be of any type.

Creating a new map



So, a literal map is surrounded by braces.

Keys and values must be separated by a colon and key/value pairs must be delimited by a comma.

Note that the colon and the comma (here) are NOT 8th words, but just syntax.

Retrieving a value for a specific key






In order to retrieve the map itself, we need G:@.
In order to retrieve the value for a key we need m:@.

Storing a value in a map using m:!







Note that the order of key/value pairs is arbitrary! This kind of container is not suited for sequential in order access.

Removing a key with it’s value from a map using m:-


Iterating over a map using m:each


Note that this works almost exactly the same as for arrays.

Conclusion on maps

There are a few more very useful words for maps.

For now I will leave you with “homework”

  • Study the SED’s for the array and map namespace
  • Try out some words for yourself
  • Never ever give up!
  • Post any interesting piece of code in the forum

If you need help, please ask any question and report any problem you may have in the forum! Today I made a stupid mistake and finally asked in the forum. It’s really not a shame whatsoever.

More info about 8th

8th Website:   http://8th-dev.com
8th Forum:   http://8th-dev.com/forum
My YouTube Channel:   https://goo.gl/DscYVD
My BLOG:   http://goo.gl/n1NocJ
The Big 8th Lessons Book:  http://goo.gl/qDa6fH

02 February 2016

Lesson 14 – Using arrays in 8th – part 2

More on arrays

Now we are going to see a few more advanced words in the a (array) namespace.

Iterating over an array – the word a:each

Later we will see that 8th has special words for iterating / looping.

However, there are also words like a:each that make it very easy to use iteration under the hood, without having to bother with the details.

The SED of a:each is \ a w – a

  • a = input array
  • w = the helper word

The SED of show (in our example below) is \ index value --

  • index = index of current array item
  • value = value of current array item

So a:each is such a word, that takes another word as a parameter (as we saw in the previous lesson).

The show word will be handed the value of the item at TOS and it’s index in 2nd position on the stack.

Example





Note that we have to use swap in order to show the index before the value!

Note that 8th arrays can contain values of different types (unlike e.g. in C).

Output:



Note that a:each leaves the array on the stack after executing!

Reducing an array using a:reduce

Reducing is a process like this:

  1. use an array
  2. get a start value x (which will be used as an accumulator)
  3. for every item in the array:
    1. do something with the values of the current array element and x (and also consume them)
    2. push the result on the stack; that value will then be used as the x value in the next iteration

The SED of a:reduce is \ a w x – x

  • a = input array
  • w = the helper word
  • x = initial value, also used as an accumulator

The SED of sum (just an example word below) is \ value x -- newx

  • value = value of current array item
  • x = initial value, also used as the accumulator

Example


Output:



Filtering an array using a:filter

This word uses a helper word that returns either true or false.

Only if that helper word retruns true, the corresponding element will be put in an output array.

The SED of a:filter is \ a1 w – a2

  • a1 = input array
  • w = the helper word
  • a2 = output array

The SED of iseven (just an example word below) is \ value -- boolean
value = value of current array item
boolean = true or false

Example


Note that the not word regards the value 0 (zero) as false! So when value 0 is encountered, not will output true and otherwise false.

Output:


More info about 8th

8th Website:   http://8th-dev.com
8th Forum:   http://8th-dev.com/forum
My YouTube Channel:   https://goo.gl/DscYVD
My BLOG:   http://goo.gl/n1NocJ

30 January 2016

Lesson 13 – Anonymous words and words as parameters

A bit more word related stuff

Before we begin to explore the namespace a (arrays) further, we first need to explain a bit more about words.

When we define a word we start with the : (colon word) and end with the ; (semi colon word). 8th will compile the word and after that the word can be invoked by other parts of your code.

We call this kind of words named words, because you give them an explicit name.

Anonymous words

In some cases it is handy to have a word definition without giving that definition a name. For such cases there are anonymous words.

Just as the colon and semi colon words begin and end the definition of a named word, the opening and closing parentheses words begin and end an anonymous word, like so:
       (  “Hi there “  .  cr  )

Note that these are all 8th words and must be space delimited!

Callback words – words used as parameters for another word

Sometimes an 8th word is needed as a parameter by another word.

If you would write down such a helper word right away, things go awry, because then that helper word is being invoked instead of passed as a parameter.

Example 1

  • imagine we want to use an arbitrary word x which in turn needs a helper word y during the execution of that word x
  • suppose that the SED of word x is \ helperword –

If we now wish to invoke x and do something like this:
y x

the following happens:

  • 8th will invoke the word y instead of handing it to x as a parameter
  • then x expects a parameter (the word y) to be on the stack, which won’t be the case

But that is not what we want at all! In order to prevent 8th from invoking the word y, we need to tell 8th that it should hand over the definition of y to x.

Especially for such cases there is the    (single quote) word.

Example 2

So now we can invoke x using the helper word y like so:
‘   y   x

and everything works well!

Note that the     word must be a plain quote.  (Microsoft Word shows it here as a bottom up comma. For code always use a plain tekst editor). The same applies to double quotes.

Anonymous word used as a callback

Because of the nature of anonymous words, you can also define a helper word as mentioned above as an anonymous word.

In that case you don’t need to quote the anonymous word.

So now we can invoke x using an anonymous helper word like so:
(  “Value = “  .  .  cr  ) x


How to invoke a helper word y from a word x

There is a word called w:exec which can be used to invoke another word.

Example

To complete the picture we now create a small program demonstrating the different features we talked about.

We will put a numeric item on the stack and show the result of adding 100 to it.



We do this in 3 different ways. Here is the output:



More info about 8th

Central website for 8th is: http://8th-dev.com

YouTube Channel here: https://goo.gl/DscYVD

BLOG here: http://goo.gl/n1NocJ


25 January 2016

Lesson 12 – Using arrays in 8th – part 1

Arrays

An array is a special form of a variable.

Instead of just 1 value, you can store a lot of values in it. It has a bunch of slots.

Normally you would require a separate name for each slot. But when you use an array, you only need the name of the variable containing that array and the index of the specific slot where a specific value is (or will be) stored.

Define an empty array

Defining an empty array can be done like so:
[] var, arr1

It seems like we just define a normal variable arr1 here. However, note that the [] we push onto the stack first is an empty array!

Note that [] is not a single character but the 2 characters [ and ] concatenated.

Define an array with initial values

You can also define an array with initial values, like so:
[100, 200, 300] var, arr2

What is a variable and what is an array?

In effect an 8th variable is a pointer to a “value”. The variable itself has no specific type, the value it points to has a type.

Using the @ word, you dereference the variable and point now directly to the value which has a specific type.

When the value pointed to happens to be an array, a specific action is required to get the desired array element.

In effect an array is a series of pointers to each array element. An array is a type itself. However, the array elements can be of different types. 

So first we have to “find”a specific array element before we can establish the type of that element.

Using the a:@ word in combination with an array index number we can now dereference the array element itself.

Dereferencing an array and it’s elements

This is the tricky part of arrays in 8th.

In languages like C or Java, you can reference array elements like so:
arr1[3]

We would expect that we could retrieve the same in 8th something like so:
arr1 3

However that is NOT the case! In 8th we must dereference the variable first using @ and then dereference the array element using an index and  the a:@ word:
arr1 @ 3 a:@

So, effectively:
  1. you first dereference the variable that holds your array using @
  2. then you use the number of the element to be retrieved from that array (3 in this example)
  3. and finally you use the a:@ word to retrieve the corresponding element value

You could compare it with a chest of drawers. When you need something in drawer 3:
  1. you must first reference (go to) the specific chest (array)
  2. then you use the number of the drawer (here the number 3)
  3. and finally you open that drawer and retrieve it’s contents

An example to show what happens:


Explanation of each step:
  1. .s                                   \ show that stack is empty
  2. [10, 11, 12, 13] var, a      \ define an array named a with 4 elements
  3. .s                                   \ show that stack is empty
  4. a @ . cr                          \ here we dereference the variable and get the value
  5. [10,11,12,13]                   \ it appears that that value is a 4 element array
  6. .s                                   \ show that stack is empty
  7. a @ 3 a:@ . cr                \ now we dereference the array element 3 using the word a:@
  8.                                       \ it appears that element 3 is the number 13, which means that
  9.                                       \ 8th uses index 0 (zero) for the first element!
  10. .s                                   \ shows that the stack keeps the reference to the variable a
  11.                                       \ please have a look in the manual for the SED of a:@
Because the reference is left on the stack (in step 7) you could go on referencing other elements like so:
     0 a:@ . cr      \ This would fetch array element 0 (zero) which is the first element: 10.

More info about 8th

There is a central website for 8th here: http://8th-dev.com/

23 January 2016

Lesson 11 – 8th general program structure

More than a REPL is needed

So far we only have shown the REPL, the interactive 8th console.

In order to create complete programs we need to expand our possibilities a bit.

Using a text editor

We will need a (simple) text editor to write an 8th program.

These days there are all kinds of advanced tools, like IDE’s (Interactive Development Environment). However, for our purposes we only need a simple editor.

The editor I am using is called Textpad and costs a little. I also created a simple, but nice looking 8th syntax highlighter for it. You can ask in the 8th forum about this.

A few possible (free) editors (in no specific order):


NOTE stay away from text processing programs like MS Word, Wordpad, Open Office, Libre Office etc. Those “editors” make heavy use of markup language. But we need a strict plain text editor for programming purposes!

Program structure in 8th


  • if we reference a variable x from within a word w we have defined, that variable x must have been defined before the definition of word w
  • if we reference a word w1 from within a word w2 we have defined, that word w1  must have been defined before the definition of word w2 (there is a special case (deferred words) which we will explain later)
  • at the end of a program you should define the special word app:main which is the word invoked automatically when your 8th program starts
  • the app:main definition should normally end with the bye word. For this rule there are 2 valid exceptions:
    • in GUI apps quitting 8th will be done elsewhere in the program; you must leave out bye there
    • for debugging reasons; from version 16.01 onwards there will be a word available to start the REPL; you could then use that word, instead of bye to debug your program

Work flow


  1. open your text editor
  2. open a command prompt / terminal
  3. switch to the directory where your source is stored
  4. create, add or modify a small piece of code in the text editor; never change big pieces of your program at once, because then it is very difficult to track bugs
  5. start your program in the command prompt / terminal:    8th   progname.8th
  6. check the results of your program
  7. go back to step 4

Our first program

In the text editor I now show you the first (very simple) program:


We then open a Command Prompt or Terminal, change to the directory where the source is located and then start the program:

Namespaces revisited

In the program we used the with: word. Doing so, 8th will search for words and variables  in this namespace as well.

If you don’t use with: you will need to qualify the defined words / variables in such a namespace. In this example case: @arie.space:squared

NOTE that it is possible to have the same word or variable name in different namespaces. In that case the word found first (in the search order of 8th) will prevail!

Conclusion

Of course this is just the beginning. You should get acquainted with this stuff and try out small snippets of code.

Do not hesitate to sprinkle .s words throughout your code. That way you can easily see what is happening on the stack!

More info about 8th

There is a central website for 8th here: http://8th-dev.com/

Video

You can watch the complementary video here: https://youtu.be/SmiRwTNWkSs

18 January 2016

Lesson 10 – Create your own words in 8th

A first step towards real programming in 8th

In every programming language there is something like a subroutine, procedure and/or function. I will call this lot “function” hereafter.

Such functions consist of a piece of code in that language. In many cases you can have local variables in such functions.

On entry such functions can get input arguments / parameters. Also in some cases some output can be returned and / or printed in one or another way.

Functions in 8th are called words

In 8th there is an equivalent to functions, called words.

Since, as we already know, 8th is built around the stack concept, almost all words fetch their input from the stack and push their result(s) back onto the stack.

Since 8th does not have local variables, we should use namespaces to create manageable subsets of words and variables.

Unspoken rules when defining words

When we define a word ourselves a set of “rules” should be followed:

  1. define your own words in a separate namespace (previous lesson)
  2. create documentation, at least in the form of a SED
  3. keep your word short
  4. your word should comprise a small, easy to understand, task
  5. your word should be as readable as possible

How to define a word

In order to create a new 8th word, we need 2 more words:

  • : (the colon) to start a word definition
  • ; (the semi colon) to end a word definition

So a word definition in it’s bare form looks like this:
: <name> <code> ;

NOTE that every 8th word must be space delimited, including these 2 words!

A first example

We will create a word add3 that adds 3 to it’s input argument and prints the result.

The SED would be:
add3 \ n –

and the definition:
: add3 3 + . cr ;

The reason that add3 does not leave any output on the stack is because the . word consumes the result of the + word. If you are in doubt you should look up the SEDs of these words!

Have a look at the REPL output:

Check that stack is empty.




Define add3.


Execute add3 with input 5.

Output is 8.



Stack is empty again.



Check the unspoken rules

As far as I can tell this word adheres to rules # 2, 3, 4 and 5 but not to rule # 1.

We can check that it is defined in the default namespace user.

When we execute words/ G: we will discover that add3 has been defined in namespace G.


Second example – using our own namespace

In this example we will use our own namespace myspace.

Check that stack is empty.



Switch to namespace myspace.
Define add3 word.

Test add3 with input 7.
Result is 10.


Check that stack is empty.

List all words in myspace.



Only one word namely add3 found in namespace myspace.





Some remarks about namespaces

You can also switch to already existing namespaces (not only new ones) like G:
ns: G

When you are in some namespace you may need to qualify your word name with the namespace it has been defined in, like: myspace:add3


Conclusion

It is very easy to define one’s own words.

But try to remember the unspoken rules. Not only they guide you to good coding habits, but they also protect you from very nasty errors, which are almost impossible to debug.

In my examples I showed the stack before and after execution. That was for a good reason.

You should not be ashamed to have a pencil and paper next to you when writing and testing a program. You should write down the expected contents of the stack before and after executing each and every (intermediate) word.

More info about 8th

There is a central website for 8th here: http://8th-dev.com/
Corresponding YouTube videos here: https://goo.gl/6Ti2pI

14 January 2016

Lesson 9 – Variables and namespaces in 8th



Global variables are undesired

In the programming world there is consensus about the rule that global variables should be avoided.

Global means that a variable can be seen and manipulated from any part of a program.

It is far better to have local variables. These can only be seen and manipulated in a specific small part of a program.

Variables in 8th

As we said in a previous lesson we have a special solution for this in 8th.
When we normally define variables (like we did before) these variables will be part of the namespace user which is the namespace where 8th stores variables and words by default. Example:


In line 1 we define the numeric variable named chris.

In line 2 we push the variable itself (not the contents of it) on the stack.

In line 3 you can see that the variable effectively is called user:chris.

Creating variables in your own 8th namespace

In 8th you can create your own namespaces freely. Example:


In line 1 we create and make active a new namespace called myspace using the ns: word.
For now this means that variables defined after making this myspace active, will be part of this namespace.

In line 2 we define a new variable named mike.

In line 3 we push the variable mike (the definition, not the contents) on the stack and display the stack

In line 4 we can see that mike now belongs to the namespace myspace, so the qualified name is myspace:mike

Qualifying names

In general it is best practice to qualify variables and words by namespace, like myspace:mike in the previous paragraph.

That way it is always clear what you mean.

The same applies to words. So it is better to use n:+ for addition than barely +.

Further use of namespaces

In a next lesson we will see that we can also create pieces of our own code, which will be called words, as is the case with standard 8th word definitions.

Those words can also be put in a desired (and/or self created) namespace.

Using standard (default) 8th namespaces

When you create new words or variables that rightly belong to one of the standard namespaces already defined in 8th, you can define your own stuff there.

However, in almost any case it is better to create your own separate namespaces. The main reason to do so is that the names you choose for your words or variables might already be taken by standard 8th.

Also you’d have to check with each and every new 8th version if new conflicting names exist.

Unique namespaces best practice

Namespace names can be split in multiple parts using dots between the parts.

Here we see that the namespace consists of 2 parts, @john and space1.

This is BTW a very nice naming convention for your own namespaces.

Use your own name preceded by 1 or 2 weird characters (like @) as a prefix and only create namespaces with that unique prefix.

More info about 8th

There is a central website for 8th here: http://8th-dev.com/
Corresponding YouTube videos here: https://goo.gl/6Ti2pI

13 January 2016

Lesson 8 – Variables in 8th

Two ways to initialize a variable

In 8th there are 2 words: var and var, which initialize a variable.

Retrieving a variable is done with the @ word.

var initializes a numeric variable giving it the initial value 0 (zero):
SED:  var \ <name> --

Example: 



 var, intializes a variable with the value in TOS at the time the variable is defined:
SED:  var, \ x <name> --

Example 1:



 So, x (from SED) has the value “my value” and <name> (from SED) is y.

Example 2:








Now we have redefined the variable y (in the same REPL session):

Note that:
8th explicitly shows that we overwrite the previous definition of the variable
we redefined the variable with an other datatype, which is not a problem in 8th

Setting variables

You can set an already defined variable to a given value, using the ! word.
Example:









Note again that a variable can take values of any 8th datatype!

Characteristics of 8th variables


  • 8th variables are “just containers”. Variables do NOT have a datatype. However the contents (or value) of variables always have a valid 8th datatype
  • 8th variables are ALWAYS GLOBAL to the namespace they are defined in
  • usage of variables should be MINIMIZED. In almost all cases you can do most of the work using the stack only.

More info about 8th

There is a central website for 8th here: http://8th-dev.com/

Video

Watch complementary video here

Lesson 7 – Get help in 8th

Getting help with 8th

If you have looked into the 8th manual, you’ll be aware of the fact that there are a lot of words (functions) defined in 8th.

In order to find information quickly, there are a few helper words to accomplish that.

Extended SED (Stack Effect Diagram)

First we need to complete your understanding of SED’s.

Because SED’s are used to document the behaviour of words we need to extend it a little. We saw that:
The items before the dashes are the “input” items on the stack
The items behind the dashes are the “output” items on the stack

However, there are also words that take information directly from the REPL. In that case there is a special form of “input item” in angle brackets. Such item has to follow the word immediately.

The word help


help \ <name> --
Example: help apropos

The result is the documentation for the specific 8th word apropos.

NOTE: <name> must be a valid 8th word

The word apropos


apropos \ <text> -- 
Example: apropos  cls

The result of this is a list of documentation sets on all the words having the piece of text “cls” in their documentation.

NOTE: <text> is just a piece of text which is searched for in the documentation of all 8th words.

The word words/


words/ \ <filter> --

Example 1: words/ n:

   The result of this is a list starting with the number of words matching the filter (in this case we
   request all words in the n: namespace) followed by the individual matching words

Example 2: words/ cls

 






Here we see multiple results.

Showing the contents of the stack

Last but not least there is the .s word, which we saw earlier.

That word is definitively very important to know what is going on in your program.

More info about 8th

There is a central website for 8th here: http://8th-dev.com/

Video

Watch the complementary video here

Lesson 6 – A look at datatypes and namespaces in 8th


Updated version of this lesson


Because of a few breaking changes in 8th, this lesson uses some new specs:

  • before 16.02 new words and variables were stored by default in class G 
  • from 16.02 onward they will be stored in the default namespace called user
  • Before 16.03 the term class  and cls: was used
  • From 16.03 onward we use the term namespace and namespace ns: instead

A last remark on calculations

In the previous lesson I used the term operator for the + - * and / word. As far as 8th is concerned these words are not special. Those words just happen to act as operators.

Datatypes

So far we have only used (whole) numbers in our examples.

In 8th there are a few basic datatypes:

  • Numbers;    some examples:
    • -11.3   gives -11.30000 (float)
    • 22.3e-3 gives   0.02230 (e notation)
    • 22.3E-3 gives   0.02230 (e notation)
    • 12      gives   12      (integer)
    • 0xff    gives  255      (hex)
    • 0Xfe    gives  254      (hex)
    • $10     gives   16      (hex)
    • &77     gives   63      (octal)
    • %1111   gives   15      (binary)
    • #123    gives  123      (# forces decimal base)
  • Strings like “The big brown fox”. The \ (backslash) may be used as an escape character for:
    • "       double-quote    ASCII 34
    • a       alarm           ASCII  7
    • b       backspace       ASCII  8
    • f       formfeed        ASCII 12
    • n       newline         ASCII 10
    • r       carriage-return ASCII 13
    • t       tab             ASCII  9
    • v       vertical tab    ASCII 11
    • x       next 2 chars are hex digits (\x20 is space)
    • u       next 4 chars are hex digits (\u201c is )

But there are a lot more (and more advanced) datatypes as well.

8th namespaces

As you may know, a lot of programming languages have namespaces.

A namespace is what it says, a separate space for names. That means that you can use the same name for different words or variables, but then they have to be in different namespaces.

In 8th, when you define a word or create a variable, these will always be defined in some namespace.

If you don’t specify in which namespace, they will be stored in the default namespace named user.

An example to clear the fog

The datatype number belongs to the namespace n.

All words related to numbers are grouped together in that namespace. That means the following:
words like   +   -   *   etc. are defined in the n namespace
those words are actually the words   n:+   n:-   n:*
the n is the namespace, the colon : separates the word from the namespace
this allows that there are other words called   +   *  -  in another namespace!

An example of a word having the same name in another namespace is   s:+   The namespace s is the “string” namespace and   s:+   happens to be string concatenation.

Standard namespaces in 8th

There are a lot of namespaces already defined in 8th. We will encounter them later. Have a look in the 8th manual!

You, being the developer may freely add new words to an existing namespace.

User defined namespaces in 8th

The developer may also freely define new namespaces.

That way a neat way exists to separate different pieces of code and avoid clutter and duplicate names.

This is especially important because 8th does not have the concept of local variables. You could say: namespaces are the 8th way of having local variables.

Intermezzo

When we wish to print the item at TOS (Top Of the Stack) we can use the  .  (dot) word.

In order to print a newline we use the   cr   word.

Without cr the next prompt is “glued” to the output.



With cr the line is terminated neatly.




Representation of a namespace

Internally a namespace is represented by a unique number.

It is easy to determine the namespace for a given item using the word >kind like so:

  • 1 >kind . cr     \ gives 1 (represents the n namespace)
  • “abc” >kind . cr \ gives 2 (represents the s namespace)

More info about 8th

There is a central website for 8th here: http://8th-dev.com/
Correspondig videos: https://goo.gl/DscYVD