/*
 *  weakref.jc
 *
 *  Demonstrates using weak references in JewelScript.
 */

import stdlib;
using stdlib;

/*
 *  class Buddy
 *
 *  This small test class can hold a reference to a "buddy" object of the same type.
 *  In order to avoid memory leaks that can occur when two reference counted objects
 *  reference each other, this class uses a weak reference to store the reference to
 *  the buddy.
 */

class Buddy
{
    method Buddy( const string name )
    {
        this.buddy = null;
        this.name = name;
    }

    method SetBuddy( Buddy buddy )
    {
        this.buddy = buddy;
    }

    method PrintBuddy()
    {
        print({ this.name, " says: My buddy is ", buddy.name, "\n" });
    }

    weak Buddy     buddy;
    string          name;
}

/*
 *  function main
 *
 *  This is the main entry-point function of the script.
 *  We create two buddies here and have them reference
 *  each other.
 */

function string main(const string[] args)
{
    Buddy a = new Buddy( "Buddy A" );
    Buddy b = new Buddy( "Buddy B" );

    a.SetBuddy( b );
    b.SetBuddy( a );

    a.PrintBuddy();
    b.PrintBuddy();

    return "";
}