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.
opcode defines a
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
find_type I1, "Foo" new P3, I1
opcode also checks to see if the class
defines a method named “_ _init”
and calls it if it exists.
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 ...