O'Reilly logo

Perl 6 and Parrot Essentials, Second Edition by Leopold Tötsch, Dan Sugalski, Allison Randal

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Classes and Objects

Parrot’s object system is a new addition in version 0.1.0. Objects still have some rough edges (for example, you currently can’t add new attributes to a class after it has been instantiated), but they’re functional for basic use.

This section revolves around one complete example that defines a class, instantiates objects, and uses them. The whole example is included at the end of the section.

Class Declaration

The newclass opcode defines a new class. It takes two arguments, the name of the class and the destination register for the class PMC. All classes (and objects) inherit from the ParrotClass PMC, which is the core of the Parrot object system.

newclass P1, "Foo"

To instantiate a new object of a particular class, you first look up the integer value for the class type with the find_type opcode, then create an object of that type with the new opcode:

find_type I1, "Foo"
new P3, I1

The new opcode also checks to see if the class defines a method named “_ _init” and calls it if it exists.

Attributes

The addattribute opcode creates a slot in the class for an attribute (sometimes known as an instance variable) and associates it with a name:

addattribute P1, ".i"                # Foo.i

This chunk of code from the _ _init method looks up the position of the first attribute, creates a PerlInt PMC, and stores it as the first attribute:

classoffset I0, P2, "Foo" # first "Foo" attribute of object P2 new P6, .PerlInt # create storage for the attribute setattribute P2, I0, P6 # store the first ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required