A class is a xtype's type with fields to define behavior for its instances. It has the xtype_*
and luaoop
(when built) special fields.
An instance is a table with behavior defined by a specific class.
The library is built on xtype, thus type checking and order of inheritance are already specified by its documentation.
A class inherits from its base classes fields, except for the xtype_*
and luaoop
fields.
An instance inherits from its class fields (with inheritance), except for xtype_*
, luaoop
and those starting with __
, which are special class fields.
|
Inheritance of fields is not dynamic (cached for performance) and is built by The build of a class is independent of other class builds and will affect all its instances. The class is also partially built from the base classes when created (i.e. the class inheritance, not the instance inheritance).
|
Special methods are prefixed by __
.
construct |
called at initialization |
||
destruct |
called at garbage collection
|
call |
like the metamethod |
tostring |
like the metamethod |
unm |
like the metamethod |
len |
like the metamethod |
bnot |
like the metamethod |
xtype op multifunctions are assigned to the corresponding metamethods in the instance metatable.
There is no private/protected mechanism in Luaoop.
local function pmethod(self)
end
local privates = setmetatable({}, {__mode = "k"})
function Object:__construct()
privates[self] = { a = 1, b = 2 }
end
function Object:method()
local p = privates[self]
p.a = p.a*p.b
end
-- Create a new class.
-- Base types can be classes or other xtypes.
--
-- name: human-readable string (doesn't have to be unique)
-- ...: base types, ordered by descending proximity, to the least specific type
-- return created class (an xtype)
class.new(name, ...)
-- ALIAS class(name, ...)
-- Create instance.
-- Will build the class if not already built.
--
-- classdef: class
-- ...: constructor arguments
-- return created instance
class.instantiate(classdef, ...)
-- ALIAS Class(...)
-- Build/re-build the class (class and instance inheritance).
-- Will add the luaoop field to the class.
--
-- classdef: class
class.build(classdef)
-- Get the class metatable applied to the instances.
-- Will build the class if not already built; useful to apply class behaviour
-- to a custom table.
--
-- classdef: class
-- return metatable
class.meta(classdef)
A = class("A")
a = A()
xtype.is(A, class) -- true
xtype.is(a, A) -- true
A = class("A")
function A:test() print("a") end
B = class("B")
function B:test() print("b") end
C = class("C", A, B) -- inheritance from A and B
function C:test() -- force the usage of B:test()
B.test(self)
end
A = class("A")
function A:__construct() print("A") end
B = class("B", A)
function B:__construct()
A.__construct(self) -- call parent A constructor
print("B")
end
vec2 = class("vec2")
function vec2:__construct(x, y) self.x, self.y = x, y end
xtype.op.add:define(function(a, b)
return vec2(a.x+b.x, a.y+b.y)
end, vec2, vec2)