13 line class module

Showcase your libraries, tools and other projects that help your fellow love users.
Post Reply
User avatar
veethree
Inner party member
Posts: 877
Joined: Sat Dec 10, 2011 7:18 pm

13 line class module

Post by veethree »

Code: Select all

local mt = {__index = function(self, key) return self.__baseClass[key] end, __call = function(self, ...) return self:new(...) end}
local class = setmetatable({ __baseClass = {}, __type = "class" }, mt)
function class:new(...)
    local arg, cls = {...}, {__baseClass = self}
    setmetatable(cls, getmetatable(self))
    if type(arg[1]) == "table" and arg[1].__type == "class" then
        cls.__super, cls.__BaseClass = arg[1], arg[1]
        setmetatable(cls, getmetatable(arg[1]))
    end
    if cls.init then cls:init(...) end
    return cls
end
return class
Wanted to make myself a nice OOP library and got a case of the fuckarounds and decided to shove it into as few lines of code as i could.

Code: Select all

class = require "class"

-- Defining a class
Person = class()

-- Setting init function
function Person:init(name, age)
    self.name, self.age = name, age
end

-- Class method
function Person:speak()
    print("Hi my name is " .. self.name .. " and i am " .. self.age .. " years old.")
end

-- Inheritance
-- Definding a child class
Worker = class(Person)

-- Overwriting the parents class init function
function Worker:init(name, age, occupation, salary)
    self.__super.init(self, name, age) -- Calling the parents class init function because i just overwrote it
    
    -- Worker specific properties
    self.occupation, self.salary = occupation, salary
end

-- Same deal for the Worker's speak function
function Worker:speak()
    self.__super.speak(self)
    print("I work as a " .. self.occupation .. " for a salary of $" .. self.salary)
end

p1 = Person("Joe", 23)
p2 = Worker("Alex", 34, "Doctor", 100)

p1:speak()
p2:speak()
I bet there's a huge problem with my approach in this but it was a pretty fun project
User avatar
dusoft
Party member
Posts: 654
Joined: Fri Nov 08, 2013 12:07 am
Location: Europe usually
Contact:

Re: 13 line class module

Post by dusoft »

Looks alright, but there already exist multiple classes for OOP:
https://github.com/love2d-community/awesome-love2d#oo
pauljessup
Party member
Posts: 356
Joined: Wed Jul 03, 2013 4:06 am

Re: 13 line class module

Post by pauljessup »

Nice getting the code footprint so small! 13 lines. Very cool.
Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 9 guests