class


Type    
meta class table
Library
core
Return value


See also 
Object


Overview


  The luasopia library has a concise class structure. A class is generated by the following.


local C = class()

The following means the class 'C' inherits a class 'B'.

local C = class(B)

By this, the C object can use all the methods in class B. If there is no base class, Object class is inherited by all the classes defined.

  The defined class must have an init() method that is a constructor.

Example


  Let define a 'Point' class that has x and y value.

local Point = class()

function Point:init(x, y) -- this is must be defined
    self.x = x
    self.y = y
end

function Point:getLength()  -- public method
    local xs = self.x * self.x
    local ys = self.y * self.y
    return (xs+ys)^0.5
end

The object of 'Point' can be generated as follows.

local pt1 = Point(3,4)
local pt2 = Point(22,33)
print(pt1.x, pt1.y) -- prints 3  4
print(pt1:getLength()) -- prints 5


The 'Point' method can be inherited by other classes as the following.

local Point3 = class(Point)

function Point3:init(x, y, z) -- constructor must be defined.
    Point.init(self, x, y) -- this calls the constructor of base class.
    self.z = z
end

By this, the 'Point3' object can call the 'getLength()' method in the 'Point' class.

local pt3 = Point3(2,4,4)
print(pt3.x, pt3.y, pt3.z) -- prints 2  4 4

The object pt3 can also call getLength() method.

local pt3 = Point3(2,4,4)
print(pt3.x, pt3.y, pt3.z) -- prints 2  4 4
print(pt3:getLength()) -- prints 4.47213595499958

Extra method must be defined to get the length of (x,y,z) point.

local Point3 = class(Point)

function Point3:init(x, y, z) -- constructor must be defined.
    Point.init(self, x, y) -- this calls the constructor of base class.
    self.z = z
end

function Point3:getLength3() -- additional method
    local xs = self.x * self.x
    local ys = self.y * self.y
    local zs = self.z * self.z
    return (xs+ys+zs)^0.5
end


local pt3 = Point3(2,4,4)
print(pt3.x, pt3.y, pt3.z) -- prints 2  4 4
print(pt3:getLength()) -- prints 4.47213595499958 (== sqrt(2*2+4*4))
print(pt3:getLength3()) -- prints 6

  If a new getLength() method is defined in Point3, it overrides the getLength() method in Point class.

댓글 없음:

댓글 쓰기