lua 面向对象
概述
lua 的面向对象是通过 table 类型, 使用元表实现的
lua 的继承简单理解来就是方法的一层层包裹, 支持方法重写
普通类
示例程序
Rectangle = {area = 0, length = 0, width = 0} function Rectangle:new = function(o, length, width) o = o or {} setmetatable(o, self) self.__index = self self.length = length or 0 self.width = width or 0 self.area = length * width return o end function Rectangle:printArea() print("printArea: ", self.area) end r = Rectangle:new(nil, 10, 20) r:printArea()
继承
示例程序
local Shape = {area = 0} local mtShape = {__index = Shape} function Shape:new() local o = {} return setmetatable(o, mtShape) end function Shape:printArea() print("printArea:" .. self.area) end local Rect = Shape:new() local mtRect = {__index = Rect} function Rect:new() local o = {} return setmetatable(o, mtRect) end r = Rect:new() r:printArea()