Object‐Oriented Programming
Our approach to objects highly mirrors that found in prototypal languages where an object is literally a table and can in some ways be used similarly.
In particular,
- Objects are opt-in.
- Existence of objects does not conflict with usage of tables as a dictionary.
It was our intent that the programmer does not have to use the paradigm and that tables can still be used separately.
require('object', Object)
update=Object.update
Ship={
x=1
y=1
rel move(this,x,y,this2)
update(this,{'x'=x and 'y'=y},this2) //this2=this+{'x'=x and 'y'=y}
}
ship=Object.create(Ship)
print(ship.y) //1
shipAfterMoving=ship.move(1,2)
print(shipAfterMoving.y) //2
The method Object.create
essentially marks a table as an 'object'. Typically, a parameter this
or self
refers to the object itself and is hidden in further calls.
Much like logic programming, object-oriented programming is often accompanied by an intuition. There's something the code tries to represent and a mechanical approach by which it does so.
Intuition
A common intuition in object-oriented programming is to say a class represents the ideal concept of a ship while objects make up individual ships.
While the concept of a Ship is unchangeable, individual ships can change and hold distinct properties.
A given ship may deviate from the ideal ship as well as other ships. An object ship1 may be in a different position than ship2.
In modeling our class, we decided on its related properties--namely, x and y coordinates indicating its position, and associated methods--a move relation that changes its coordinates. A ship is able to move through the oceans.
ship=Object.create(Ship)
A ship is then created using the create relation. Ship may be called its class or prototype.
Procedural Interpretation
It's common in prototype-based programming to simply use a table or similar data-structure for the object and/or classes[1]. What happens then is,
-
create
makes a new tableship
. - The table
ship
is marked as an "object". -
Ship
is established as the prototype ofship
. - If the programmer tries to access a property of an object, it first looks in the object itself, and if it's not found, it looks into its prototype.
- The first parameter of an object call is hidden, hence
ship2=ship.move(ship,1,2)
is shortened toship2=ship.move(1,2)
.
In our example, shipAfterMoving.y
is immediately found to be 2. However, ship.move
requires lookup as move
only exists in the prototype.
[1] Thus, classes don't technically exist. What we have is objects that may be described as "class-like". See Self: The Power of Simplicity.