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:

2 Comments:

At 12:36 AM, Anonymous Anonymous said...

good stuff!

 
At 9:14 PM, Anonymous Anonymous said...

good morning bros. I'm really into shoes and I had been searching allowing for regarding that meticulous make. The prices seeking the shoes are around 180 bucks on every page. But for all I bring about this location selling them for half price. I in reality like these [url=http://www.shoesempire.com]prada sneakers[/url]. I will definetly buy them. what is your opinion?

 

Post a Comment

<< Home