lua之class
来源:互联网 发布:linux snmp 流量监控 编辑:程序博客网 时间:2024/05/21 09:27
local _class={} function class(super)local class_type={}class_type.ctor=falseclass_type.super=superclass_type.new=function(...) local obj={}dolocal createcreate = function(c,...)if c.super thencreate(c.super,...)endif c.ctor thenc.ctor(obj,...)endend create(class_type,...)endsetmetatable(obj,{ __index=_class[class_type] })return objendlocal vtbl={}_class[class_type]=vtbl setmetatable(class_type,{__newindex=function(t,k,v)vtbl[k]=vend}) if super thensetmetatable(vtbl,{__index=function(t,k)local ret=_class[super][k]vtbl[k]=retreturn retend})end return class_typeend
现在,我们来看看怎么使用:
base_type=class()-- 定义一个基类 base_type function base_type:ctor(x)-- 定义 base_type 的构造函数print("base_type ctor")self.x=xend function base_type:print_x()-- 定义一个成员函数 base_type:print_xprint(self.x)end function base_type:hello()-- 定义另一个成员函数 base_type:helloprint("hello base_type")end
以上是基本的 class 定义的语法,完全兼容 lua 的编程习惯。我增加了一个叫做 ctor 的词,作为构造函数的名字。
下面看看怎样继承:
test=class(base_type)-- 定义一个类 test 继承于 base_type function test:ctor()-- 定义 test 的构造函数print("test ctor")end function test:hello()-- 重载 base_type:hello 为 test:helloprint("hello test")end
现在可以试一下了:
a=test.new(1)-- 输出两行,base_type ctor 和 test ctor 。这个对象被正确的构造了。a:print_x()-- 输出 1 ,这个是基类 base_type 中的成员函数。a:hello()-- 输出 hello test ,这个函数被重载了。
- lua之class
- lua之class
- Lua之class
- Lua(3) ——Cocos之_语法糖class
- Lua(3) ——Cocos之_语法糖class
- Lua(2) ——Cocos之_语法糖class
- class() 高级用法 -- lua
- [Lua] class() 高级用法
- Cocos2dx-lua -- 入门-class
- lua cocos class方法
- cocos2dx-lua class
- class() 高级用法 --cocos2dx- lua
- cocos2dx lua class 继承问题
- Lua的类Class实现
- cocos2d-lua class 方法解释
- lua学习之--liu.lua
- 【Lua】Lua之面向对象
- Lua 基础之 Lua 程序
- javascript执行环境和栈
- android手机获取系统短信sqlite数据库并查看内容
- Android_百度地图BaiduMap_搜索服务
- 小例子看python缩减代码
- C#动态数据绘图graphic代码简单示例
- lua之class
- Unexpected error occurred while trying to check for group existence.
- 搜索引擎——原理技术与系统第三章
- easyui tree 的异步加载 前台的编写方法和后台的json数据格式组装方法
- poj 1703 Find them, Catch them
- 运用函数的递归求1*3*5*.......*n
- 一段时间的学习记录
- Intents and Intent Filters
- eclipse快捷键