Kinghajj's Blog

2007-09-09

Contexts as Objects in newLISP

In newLISP, contexts are great at dividing bindings into special areas to avoid
name clashes. But they can also be used to implement classes and objects.

Example 1: The Point "class"
(context 'Point)
(define (Point:Point _x _y)
  (setq x _x)
  (setq y _y))

(define (distance-from p)
  (sqrt
    (add
      (pow (sub p:x y) 2)
      (pow (sub p:y y) 2))))
(context 'MAIN)
This doesn't really look like a class, does it? But it is. Point:Point is the
constructor, and distance-from is a method. Let's see how to use this class.

Example 2: Using the Point class
(new Point 'point1)
(point1 1 1)
(new Point 'point2)
(point2 2 2)
(point1:distance-from point2)
; => 1.414213562
Wow! Isn't that something? But creating and initializing an object is a bit
of a chore as-is. Here's a simple macro to simplify this.

Example 3: Simple
(define-macro (new-object _class _name)
  (apply (new _class _name) (args)))

(new-object Point point1 1 1)
(new-object Point point2 2 2)
(point1:distance-from point2)
; => 1.414213562

Labels: