This is a simple class implementation. It was taken from the lua-users wiki. The original author is unknown.
Functions
- class(ctor)
- Creates and returns an object that represents the new class with the constructor ctor.
- class(base, ctor)
- Creates and returns an object that represents the new class with the constructor ctor which inherits from the class base.
The returned objects can be used to create new instances. Any changes to the returned object will influence all instances of this class. An example usage of this feature is the implementation of methods after the creation of the class.
Constructor
If a new instance of a class is created, the constructor will be called with the new instance as first parameter followed by any additional parameters. The constructor can be used to set any values of the new instance to either default values or values which depend on the additional parameters.
Creation of instances
In order to create a new instance of a class just call the object returned by the class function with any optional arguments to the constructor.
Methods
Every instance of a new class implements the following methods.
- obj:init(...)
- Calls the constructor of the class of the instance obj with the same arguments.
- obj:is_a(class)
- Returns true if the class is a base class of the instance obj, false otherwise.
Example
scrupp.init("Class Test", 600, 400, 32, false)
-- load required plugins
scrupp.addFile("scripts/class.lua")
scrupp.addFile("scripts/font.lua")
-- load a font
local font = Font("fonts/Vera.ttf", 20)
-- define a class for animals
local Animal = class(function(a, name)
a.name = name
end)
-- define a method that returns the name of the animal
function Animal:getName()
return self.name
end
-- define a class for dogs
local Dog = class(Animal, function(a, name, lord)
a.name = name
a.lord = lord
end)
-- define a method that returns the name of the lord of the dog
-- remark: the method getName() is taken from the base class
function Dog:getNameOfLord()
return self.lord
end
-- create an instance of the class Dog
local Hasso = Dog("Hasso", "Mr. Smith")
main = {
render = function(dt)
font:print(10,10, "Name: ", Hasso:getName())
font:print(10,40, "Lord: ", Hasso:getNameOfLord())
-- tostring() is nescessary in order to print a boolean value
font:print(10,70, "Hasso is an animal: ", tostring(Hasso:is_a(Animal)))
font:print(10,100, "Hasso is a dog: ", tostring(Hasso:is_a(Dog)))
end
}