Allocating a Koi in KoiFish

Last post dealt with Call Targets, which as quick refresher was the koi instance in which you were calling a function on, and all was fine and dandy, but how do you get an Koi instance? Allocating it of course.

Here are two Koi definitions (they, of course reside in separate files and are in the same pond, but below is the contents of each):

#KoiA.koi
koi + KoiA

fn + Main :args begin
    def b = alloc KoiB;
    call Hello@b;
end;

fn + Hello begin
    puts "Hello from KoiA";
end;

#KoiB.koi
koi + KoiB

fn + Hello begin
    puts "Hello from KoiB";
end;

So if we compiled and ran this, the output would be:

Hello from KoiB

That’s because of the call target we discussed in the last post. KoiA allocates an instance of KoiB using the alloc keyword. What that keyword nicely takes care for us, is allocating the memory required for storing our Koi on the heap, constructing the actual koi and returning the reference to it.  We took that reference and and assigned it to the b variable.

Now that we have an instance of KoiB, we call the Hello function specifying our call target as b.  If we didn’t have a call target, since it is optional, that line of code would evaluate KoiA‘s version of Hello instead. However, if KoiA didn’t have a Hello function at all, the KoiFish Compiler would not compile this program.

A quick blurb about allocating kois: once an koi has been allocated, it returns an reference to the created koi. If you do not store this reference, or at any point in the program you set the reference to something else, the koi would be deallocated and the memory freed provided that no other references point to the koi. This functionality is extremely helpful since you don’t have to worry about leaving unneeded kois hogging up precious ram. This feature is called Garbage Collection.

Advertisements
This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s