面向对象的lua

来源:互联网 发布:破解下载软件 编辑:程序博客网 时间:2024/05/07 23:16

使用lua很久了,对于如何面向对象使用lua还是想说些什么。
1. 首先我想说的是lua不适合面向对象,或者说他的基因不是为面向对象设计的。
2. lua可以使用面向对象,作为lua的一个特性可以为我们带来很多惊喜。

如何面向对象:元表

PS:不知道元表的同学请去补习基础知识

例如

Constructer = {}Constructer.__index = function(_, key)    print("I am you father")endBaseModel = {}function BaseModel.new()    setmetatable(cls, Constructer)    cls.__index = cls    return clsend

又例如

Base = {}function Base:new(o)    o = o or {}    setmetatable(o, self)    self.__index = self    return oendSpaceBace = Base:new()local instance = SpaceBace:new()

SpaceBase继承了Base的new方法,再次执行new的时候self不是Base而是SpaceBase,同样__index也是SpaceBase,因此instance的原表是SpaceBase,SpaceBase的原表是Base。即instance继承SpaceBase,SpaceBase继承Base。

多重继承

之前我们将原表设置为父类,可以实现继承,那么多重继承其实只需要将原表的__index设置为一个查找函数就可以了

local function search(k, list)    for i=1,#list do        local v = list[i][k]        if v then return v end    endendfunction createClass( ... )    local o = {}    local parents = { ... }    setmetatable(o, {__index = function(t,k)        return search(k, parents)    end})    o.__index = oend

想面向对象,搞吧。另外 提下raw get rawset:无视自定义的__index, __newindex的get set。

0 0
原创粉丝点击