Log In  


This is the second of the two little utilities I've made, the first being stream-ecs (in a separate post.)
The github project page.

prot-oo

This one's a bit more straight-forward. Prototype based inheritance/OOP. It basically just defines the base object and a few methods.

Use create to use an object as a prototype for some other object:

dog = object:create() -- use the base object as prototype
dog.sound = 'woof!'
function dog:talk()
  print(self.sound)
end

cat = dog:create() -- use the dog object as prototype
cat.sound = 'meow'

dog:talk() -- woof!
cat:talk() -- meow

You can create classes (well, not really, because prototypes, but sort of) by defining a method called init and using the new method.

vec2D = object:create()
function vec2D:init(x, y)
  self.x = x
  self.y = y
end
function vec2D:length()
  return sqrt(self.x^2 + self.y^2)
end

v = vec2D:new(3, 4)
v:length() -- 5

The new method creates a new object with vec2D as the prototype and then passes its arguments to init which initializes the object.

And sub-classes:

vec3D = vec2D:create()
function vec3D:init(x, y, z)
  self.proto.init(self, x, y) -- calls vec2D's init
  self.z = z
end
function vec3D:length() -- overrides vec2D's length
  return sqrt(self.x^2 + self.y^2 + self.z^2)
end

v3 = vec3D:new(1, 2, 3)
v3:length() -- 3.74-ish

And that's about it. Enjoy!




[Please log in to post a comment]