Lua面向对象的实现方法
来源:互联网 发布:阿里云独立ip主机 编辑:程序博客网 时间:2024/06/06 00:45
Lua实现面向对象方法大概整理了一些,分为以下两种方法:
方法一:
官方做法:
实现类:
local Class= { value=0 } function Class:new(o) o=o or {}; setmetatable(o,self); self.__index=self; return o; end function Class:showmsg() print(self.value); end local test = Class:new(); test:showmsg();
接着上面实现继承
local A = Class:new(); function A:new(o) local o = o or {}; setmetatable(o,self); self.__index=self; return o; end function A:showmsg( ) print (self.value); print("zhishi 测试啊啊 ") end local s = A:new({value=100}); s:showmsg();
结果:
0100zhishi 测试啊啊
方法二
一种更优雅的实现方式:
class.lua 代码:
local _class={}function class(super) local class_type={} class_type.ctor=false class_type.super=super class_type.new=function(...) local obj={} do local create create = function(c,...) if c.super then create(c.super,...) end if c.ctor then c.ctor(obj,...) end end create(class_type,...) end setmetatable(obj,{ __index=_class[class_type] }) return obj end local vtbl={} _class[class_type]=vtbl setmetatable(class_type,{__newindex= function(t,k,v) vtbl[k]=v end }) if super then setmetatable(vtbl,{__index= function(t,k) local ret=_class[super][k] vtbl[k]=ret return ret end }) end return class_typeend
下面看下使用:
定义一个类:
test=class() -- 定义一个基类 base_typefunction test:ctor(x) -- 定义 base_type 的构造函数 print("test ctor") self.x=xendfunction test:print_x() -- 定义一个成员函数 test:print_x print(self.x)endfunction test:hello() -- 定义另一个成员函数 test:hello print("hello test")end--调用方法test.new(1);test:print_x();test:hello();
继承的实现:
base=class() -- 定义一个基类 base_typefunction base:ctor(x) -- 定义 base_type 的构造函数 print("base ctor") self.x=xendfunction base:print_x() -- 定义一个成员函数 base:print_x print(self.x)endfunction base:hello() -- 定义另一个成员函数 base:hello print("hello base")end--子类实现child=class(base);function child:ctor() print("child ctor");endfunction child:hello() print("hello child")end--调用 local a=child.new(21); a:print_x(); a:hello();
两种方式各有优缺点,看自己了,不明白的地方留言交流。。。
0 0
- Lua面向对象的实现方法
- Lua面向对象的实现
- lua的面向对象实现
- Lua 面向对象实现
- lua实现面向对象
- lua实现面向对象
- lua实现面向对象
- 【Lua】面向对象实现
- Lua面向对象实现
- Lua面向对象实现
- lua 实现面向对象
- lua实现面向对象的特性
- lua实现面向对象的特性
- lua实现面向对象的特性
- lua实现面向对象的特性
- Lua语言中面向对象的实现
- lua面向对象是怎么实现的
- lua面向对象是怎么实现的
- 使用ES-Hadoop插件结合spark向es插入数据
- 样搭建一个便于优化的网站思路
- zoj3879 模拟
- 1094. The Largest Generation 解析
- ArcGIS10.2下载安装 License Manager、ArcGIS Desktop、ArcGIS Server软件下载及破解
- Lua面向对象的实现方法
- 【小白笔记】目标跟踪DSST改进版fDSST算法代码分析
- GIT命令
- 在tomcat服务器中部署php
- 可拖拽ListView
- 1095. Cars on Campus 解析
- Centos yum安装软件报软件包下载失败
- 如何通过Mybatis实现数据的增删改查(CRUD)操作?
- 使用git将项目上传到github(最简单方法)