This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
FUNCTION MAN!'s profile picture

Class API

Started by FUNCTION MAN!, 20 November 2014 - 06:09 PM
FUNCTION MAN! #1
Posted 20 November 2014 - 07:09 PM
We've all heard of OOP (Object-Oriented Programming), and we have most certainly seen classes in lua. But, most of the methods I found on these forums involve messing with metatables, and some other complicated things the general OOP-programmer doesn't need to mess with. So, I present you (WARNING: lame formatting incoming):


THE LUA CLASS API!
(Yes, it's comic sans. Deal with it.)

Now, let's stop with the formalities, and get to the interesting part.

To download:
pastebin get Dd11HzDK class.lua


This class API supports inheritance and a little thing I like to call 'mixins'. Mixins are just assorted collections of functions that can be reused, over and over.

Some examples:


dofile('/class.lua')
--# Simple superclass
Derp = class(Object, function(c) end)

function Derp:herp()
   print('Derp! Derpity-derp-derp-derp!')
end
--# Simple subclass

Herp = class(Derp, function(c) Derp.init(c) end)
function Herp:derp()
    print('Herp!derp!derp!')
end

print(Herp():derp())
print(Derp():herp())
--# Herp!derp!derp!
--# Derp! Derpity-derp-derp-derp!

That code defines a class, Derp, and then a subclass of Derp, the class Herp. Herp inherits the methods that Derp exposes because Herp inherits Derp. But, Derp does not expose the methods defined in Herp, because Derp->Herp but not Herp->Derp.


local Living = {}
-- The living table is the root for the Living mixin.
function Living.breathe(self)
  print('In and out. In and out.')
end

This snippet defines a simple mixin, that can be included in classes.


local Animal = class(
   function (c, name)
      c.name = name -- same as self.name = name.
   end
)
Animal('Cat'):breathe()
--# In and out. In and out.

This snipped defines a simple class, Animal, that inherits the functions of the Mixin we defined previously, Living.

You could also define add a method to animal, :sound(), and make a class, Dog, that is a subclass of Animal and overrides the sound method.

I also made an example of simple file I/O using the class system. It is avaiable on pastebin for download under the id of 'aTxhKHqS'.


[ Please no hate,
First post and all.]
Edited on 20 November 2014 - 06:12 PM
jaredallard #2
Posted 20 November 2014 - 07:51 PM
+1

Good system, and alot more modern like as opposed to tradtional OOP.

Using in ccLinux ;)/>
FUNCTION MAN! #3
Posted 20 November 2014 - 08:36 PM
:>
comp500 #4
Posted 09 April 2015 - 08:01 PM
Awesome API, but I think you forgot to put Living in the Animal definition..?

local Animal = class( -- # Living?
   function (c, name)
	  c.name = name -- same as self.name = name.
   end
)