Share Your Code

oop - no metas, no module()

Posted by se24vad, Posted on December 16, 2011, Last updated December 19, 2011

Introduction

I've build a Class - with actually just one function - for easy and very basic OOP in Lua. After some tryings I've decided to go without metatables and without module(...).
This is my own approach and of course ain't the best out there, but as far as I've tested it, it does its job very well for me, so may it do for you too.

My first approach was using metas, as everywhere suggested. And this are some illustrations of how I did that. ...I've quashed that.

The new approach is the fallowing class..
*Superparents*

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
local Superparents = {}
 
function Superparents.loadin( ... )
        if ... ~= nil then
                local files -- holds filenames to load
                        if type(...) == "string" then
                                files = {...}
                        else
                                files = ...
                        end
                
                local parentMethods = {}  -- after next step, holds all methods of loaded files
                
                        for i = 1, #files do
                                local f = files[i]
                                local r = require(f)
                                
                                for k,v in pairs(r) do
                                        parentMethods[k] = v
                                end
                        end
                
                return parentMethods
        else
                print("\nERROR: This method awaits filenames.\n")
        end
end
 
return Superparents

*usage*

1
2
3
4
5
6
7
8
local parents = require "Superparents"
local Insect = parents.loadin( "Animal" ) -- Insect is your new class, which inherits from Animal class
 
        function Insect:speak()
                self:hello() -- method from Animal
        end
 
return Insect

You can pass as many parent classes as you want. Those can be strings or a table.
e.g. "Animal", "Parent2" or {"Animal", "Parent2",}
This means you can multiple inherit too.

*DOWNLOAD*
http://www.mediafire.com/?y8v4pim7se49ew4


Replies

open768
User offline. Last seen 47 weeks 3 days ago. Offline
Joined: 6 Jul 2011

I dont get this, this is a class loader right, gets files off the disk. Then adds the methods from the loaded classes into the instance.

mybe I'm being a noob but how is this preferable to

1
2
3
4
5
6
Animal=require("animal")
 
oInstance = {}
setmetatable( oInstance, { __index = Animal} )  
 
oInstance.speak()

se24vad
User offline. Last seen 34 weeks 1 day ago. Offline
Joined: 2 Jul 2011

Works pretty much the same! But since you can only have one parent connected through metatables, my version is in advantage. I can have multiple parents. At least I needed it sometimes. Also I personally find the code being more readable and native.