Skip to content
Felyp-Henrique edited this page Aug 6, 2022 · 17 revisions

The class is a simple library to do OOP in Lua. It's inspired by the Java and Python. It's work with classes, of course, inheritance and polymorphism. There are below the list of features:

  • It's works with constructors.
  • It's works with instance methods.
  • It's works with static methods and fields.
  • It's has multiple inheritance support.
  • It's has polymorphism support.
  • It's has super keywords.

class

The class method is used to define classes. Pass as argument the definition about your class.

class(definition: table) -> class

It's define a class. You can pass as argument a table with constructor and methods.

Let's see the options of definition:

Option Description
extends List of classes to extends.
new The constructor method.
any func/var The static field of the class.

Let's see the example:

Point = class {
    STATIC_VARIABLE = 0,
    new = function (self, x, y) -- the constructor is not mandatory
        self.x = x or 0 -- instance fields
        self.y = y or 0 -- instance fields
    end,
    instance_method = function (self)
        -- any code here
    end,
    static_method = function () -- not use 'self'
        -- any code here
    end
}

super

It's used to call the super constructor and other methods.

super(self: object, superclass: class) -> table

It's call the constructor of the superclass. It's required to pass the class that you want to call the constructor. Let's see the example:

Square = class {
    extends = { Point },
    new = function (self, x, y, w, h)
        super(self, Point).new(x, y) -- here call the Point constructor
        self.w = w or 0
        self.h = h or 0
    end
}

super(self: object) -> table

It's call any method of the superclass. Let's see the example:

Square = class {
    extends = { Graphic },
    draw = function (self)
        super(self).draw() -- here call the Graphic:draw() method
        -- any code here
    end
}

object

The object is the main superclass. All classes inherit from object. The object class provided the minimal methods to work about objects.

object.to_string(self: object) -> string

It's returns string format of object.

> obj:to_string()
"table: any_number_here"

object.clone(self: object) -> object

It's returns a clone object about itself.

> local obj = object:new { x = 200 }
> obj.x
200
> local clone = obj:clone()
> clone.x
200

object.equals(self: object, other: object) -> boolean

It's returns true if other object is equals itself.

> obj1:equals(obj2)
true -- or false

object.instanceof(self: object, class: class) -> boolean

It's returns true if other object is instance of class.

> square:instanceof(object)
true
> square:instanceof(Point)
true -- or false