The Lobster Den
Home to spelling errors, deprecated HTML and wholesome fun.
Let's Build Objects in GForth
2016-01-02 04:56:00 UTC
Although FORTH is considered by many to be a procedural language, its flexibility has allowed it to adapt other programming styles as well. If you are running GForth (HINT: sudo apt-get install gforth
), you already have access to a great object oriented programming (OOP) library called oop.fs
.
The documentation is well written, but might be a little bit wordy if you just want to play around.
Below is an example of OOP in GForth that will cover 80% of the use cases:
- Instance CRUD
- Instance level variable CRUD
- Method definitions
- Method calls
- Inheritance
\ include oof.fs for GFORTH OOP. There's also mini-oof.fs, which is
\ only 12 lines long and gives you (most of) the same functionality
\ in a smaller package
include oof.fs
\ Let's define a class called "square". It inherits from the object
\ class, which is the mother of all classes in oof.fs.
\ Syntax: <parent> class <child>
object class square
\ Give it an instance method called "area"
method area
\ Give instances of square 2 cells of memory.
\ On my system, that means 128 bytes.
1 cells var length
1 cells var width
\ Now that class "square" is defined, we can implement it.
how:
\ Constructor expects 2 integers on the stack when called: width
\ and length.
: init ( n-width n-length -- self )
\ Take the first item on the stack (length) and store that into
\ the instance variable "length".
length !
\ Same thing for width
width ! ;
: area ( self -- n-area )
\ Grab length and push onto stack
length @
\ Grab width and push onto stack
width @
\ Multiply length by width
* ;
class;
\ Create a new instance of square called "my-square"
20 30 square : my-square
\ Call the method "my-square" on square instance "my-square"...
\ ... Print the return value to screen.
my-square area . cr
\ Destroy the square object (for example purposes)
my-square dispose
\ gracefully exit.
bye
I hope that helps. If you have any questions, you can always ask the friendly folks at /r/forth.