lua实现伪多态继承
2016-07-21 00:51
513 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/q741084201/article/details/51975633
通过lua的设置元表__index字段,巧妙的运用在无法索引到对象的key时会调用__index的机制,实现了伪多态、继承。
代码如下:
inheritance = {} _classTotalTable = {} function inheritance:class(father) local classVo = {} classVo.constructor = false --构造函数 classVo.father = father --父类 classVo.new = function(...) local obj = {} setmetatable(obj,{__index = _classTotalTable[classVo]}) local create create = function(c,...) if c.father then create(c.father,...) end if c.constructor then c.constructor(obj,...) end end create(classVo,...) return obj end local virtualTable = {} -- tip:当经过此继承代码return的对象增加成员变量时,放入虚表 _classTotalTable[classVo] = virtualTable setmetatable(classVo,{__newindex = function(table,key,value) virtualTable[key] = value end }) -- tip:索引不到对应key调用__index -- 索引虚表,父类有此值,给予子类 if father then setmetatable(virtualTable,{__index = function (table,key) local ret = _classTotalTable[father][key] virtualTable[key] = ret return ret end }) end return classVo end --使用事例 baseClass = inheritance:class() function baseClass:constructor() print("base:constructor") end function baseClass:wowo() print("base:wowo") end sonClass = inheritance:class(baseClass) function sonClass:constructor() print ("son:constructor") end function sonClass:wowo() print("son:wowo") end newson = sonClass:new() --base:constructor --son:constructor newson:wowo() --son:wowo阅读更多
相关文章推荐
- 在lua里实现常量_类_继承_多态
- lua面向对象实现(实例化对象、继承、多态、多继承、单例模式)
- Lua的类实现继承、多态以及setmetatable方法
- lua实现继承、多态
- lua面向对象实现-类实例化对象、继承、多态、多继承、lua单例模式
- lua面向对象实现-类实例化对象、继承、多态、多继承、lua单例模式
- Lua的类实现继承、多态以及setmetatable方法
- Lua的类实现继承、多态以及setmetatable方法
- lua面向对象实现-类实例化对象、继承、多态、多继承、lua单例模式
- lua面向对象实现-类实例化对象、继承、多态、多继承、lua单例模式
- Lua的类实现继承、多态以及setmetatable方法
- Lua的类实现继承、多态以及setmetatable方法
- Lua的类实现继承、多态以及setmetatable方法
- 【游戏开发】在Lua中实现面向对象特性——模拟类、继承、多态
- C实现类封装、继承、多态
- lua中的面向对象模拟,类,继承,多态
- Lua学习笔记5:类及继承的实现
- C语言模式实现C++继承和多态
- C语言模式实现C++继承和多态
- C语言实现C++继承和多态的代码分享