# Lua面向對象

• C++

• Java

• Objective-C

• Smalltalk

• C#

• Ruby

## 面向對象的特性

• 類: 類是可擴展的模板用來創建對象，提供狀態的初始值(成員變量)和行爲的實現。

• 對象: 它是類的實例並具有分配給自己獨立的內存。

• 繼承: 它是由變量和類的函數被其他類繼承的概念。

• 封裝: 它是將數據和函數相結合的一類內的方法。數據可以在類的外部與函數的幫助下進行訪問。它也被稱爲數據抽象。

## 創建一個簡單的類

-- Meta class Rectangle = {area = 0, length = 0, breadth = 0} -- Derived class method new function Rectangle:new (o,length,breadth) o = o or {} setmetatable(o, self) self.__index = self self.length = length or 0 self.breadth = breadth or 0 self.area = length*breadth; return o end -- Derived class method printArea function Rectangle:printArea () print("The area of Rectangle is ",self.area) end

## 創建對象

r = Rectangle:new(nil,10,20)

print(r.length)

r:printArea()

## 完整例子

-- Meta class Shape = {area = 0} -- Base class method new function Shape:new (o,side) o = o or {} setmetatable(o, self) self.__index = self side = side or 0 self.area = side*side; return o end -- Base class method printArea function Shape:printArea () print("The area is ",self.area) end -- Creating an object myshape = Shape:new(nil,10) myshape:printArea()

The area is 100

## Lua的繼承

-- Meta class Shape = {area = 0} -- Base class method new function Shape:new (o,side) o = o or {} setmetatable(o, self) self.__index = self side = side or 0 self.area = side*side; return o end -- Base class method printArea function Shape:printArea () print("The area is ",self.area) end

Square = Shape:new() -- Derived class method new function Square:new (o,side) o = o or Shape:new(o,side) setmetatable(o, self) self.__index = self return o end

## 重載基礎函數

-- Derived class method printArea function Square:printArea () print("The area of square is ",self.area) end

## 繼承完整的例子

Lua中我們可以擴展的簡單類實現，如上圖所示metatables另一個新的方法。所有的成員變量和基類的函數被保留在派生類。

-- Meta class Shape = {area = 0} -- Base class method new function Shape:new (o,side) o = o or {} setmetatable(o, self) self.__index = self side = side or 0 self.area = side*side; return o end -- Base class method printArea function Shape:printArea () print("The area is ",self.area) end -- Creating an object myshape = Shape:new(nil,10) myshape:printArea() Square = Shape:new() -- Derived class method new function Square:new (o,side) o = o or Shape:new(o,side) setmetatable(o, self) self.__index = self return o end -- Derived class method printArea function Square:printArea () print("The area of square is ",self.area) end -- Creating an object mysquare = Square:new(nil,10) mysquare:printArea() Rectangle = Shape:new() -- Derived class method new function Rectangle:new (o,length,breadth) o = o or Shape:new(o) setmetatable(o, self) self.__index = self self.area = length * breadth return o end -- Derived class method printArea function Rectangle:printArea () print("The area of Rectangle is ",self.area) end -- Creating an object myrectangle = Rectangle:new(nil,10,20) myrectangle:printArea()

The area is 100
The area of square is 100
The area of Rectangle is 200