Define a class and create an instance - tanevnikola/lua-oos GitHub Wiki
To define a class use the ft.class functor. It provides a mechanism for chaining as much namespaces as needed without a limit. The name of the class is the whole name ex: ft.class.example1.Test. This will define the class under the ft framework. To make an instance simply invoke the class definition from any place that has access to the ft table.
Lets define a class and then make a single instance
local ft = require "lib.oos"
-- define the class ft.class.example1.Test
ft.class.example1.Test() {
-- capture global print
{print = print};
constructor = function()
print("Hello World!")
end;
}
-- make an instance of the class
local instance = ft.class.example1.Test();
-- print the type
print(ft.type(instance));
Output
Hello World!
[class ft.class.example1.Test]
Calling convention
Unlike other OOP frameworks for Lua, this one is built with an idea that the : syntactic sugar creates more problems than solutions. For example, if the only way to have access to the class instance is by passing this (or self), then you have a problem if you accidentally omit to pass it or to use :. In this framework you always have this (unless you intentionally don't override it with nil or something else) since it is part of the Method Environment.
Of-course : is still valid and will pass the caller as the first argument to the method, so if you like it then freely use it.
Lets see it in practice
local ft = require "lib.oos"
ft.class.example2.Test() {
-- capture global print
{print = print};
foo = function()
print(ft.type(this));
end;
foo1 = function(this)
print(ft.type(this));
end;
}
local instance = ft.class.example2.Test();
instance.foo();
instance:foo1();
Output
[class ft.class.example2.Test]
[class ft.class.example2.Test]
Actually, calling foo1 is a bit faster. This is due to the fact that you are accessing a local variable instead of a global one (in the scope of the class this is global, by overriding it as method parameter you now have a local this which is a bit faster to access).