Lua-面向对象中类的构造
在Lua中,我们可以通过table+function来模拟实现类。
而要模拟出类,元表(metatable)和__index元方法是必不可少的。
为一个表设置元表的方法:
table = {}
metatable = {}
setmetatable(table, metatable)
或者
table = setmetatable({},{})
下面看一个简单的例子:
local t = {
k1 = "aaa"
}
local mt = {
k2 = "bbb",
__index = {
k3 = "ccc"
}
}
setmetatable(t, mt)
print("k1:", t.k1, "k2:", t.k2, "k3:", t.k3)
输出:
k1: aaa k2: nil k3: ccc
从例子可以看出,查找表元素时会从表的元表的__index键中查找。
查找一个表元素的规则如下:
除了有__index元方法外,还有__newindex,__add,__sub等很多原方法,可查看Lua文档
2.4 – Metatables and Metamethods
在了解了元表和元方法后,我们就可以模拟类的实现了。
local A = {
a1 = "this is a1",
a2 =
}
function A.new()
local o = {}
setmetatable(o, A)
A.__index = A
return o
end
function A:Print()
print("This is A:Print ")
end
local a = A.new()
a:Print()
输出结果:
This is A:Print
以上就是一个类的简单实现方式,当然,我们也可以把它的实现封装到一个function中,这样会更方便我们类的创建和使用。
下面是cocos2d引擎中,lua类的实现,以供参考:
local setmetatableindex_
setmetatableindex_ = function(t, index)
if type(t) == "userdata" then
local peer = tolua.getpeer(t)
if not peer then
peer = {}
tolua.setpeer(t, peer)
end
setmetatableindex_(peer, index)
else
local mt = getmetatable(t)
if not mt then mt = {} end
if not mt.__index then
mt.__index = index
setmetatable(t, mt)
elseif mt.__index ~= index then
setmetatableindex_(mt, index)
end
end
end
setmetatableindex = setmetatableindex_ function class(classname, ...)
local cls = {__cname = classname} local supers = {...}
for _, super in ipairs(supers) do
local superType = type(super)
assert(superType == "nil" or superType == "table" or superType == "function",
string.format("class() - create class \"%s\" with invalid super class type \"%s\"",
classname, superType)) if superType == "function" then
assert(cls.__create == nil,
string.format("class() - create class \"%s\" with more than one creating function",
classname));
-- if super is function, set it to __create
cls.__create = super
elseif superType == "table" then
if super[".isclass"] then
-- super is native class
assert(cls.__create == nil,
string.format("class() - create class \"%s\" with more than one creating function or native class",
classname));
cls.__create = function() return super:create() end
else
-- super is pure lua class
cls.__supers = cls.__supers or {}
cls.__supers[#cls.__supers + ] = super
if not cls.super then
-- set first super pure lua class as class.super
cls.super = super
end
end
else
error(string.format("class() - create class \"%s\" with invalid super type",
classname), )
end
end cls.__index = cls
if not cls.__supers or #cls.__supers == then
setmetatable(cls, {__index = cls.super})
else
setmetatable(cls, {__index = function(_, key)
local supers = cls.__supers
for i = , #supers do
local super = supers[i]
if super[key] then return super[key] end
end
end})
end if not cls.ctor then
-- add default constructor
cls.ctor = function() end
end
cls.new = function(...)
local instance
if cls.__create then
instance = cls.__create(...)
else
instance = {}
end
setmetatableindex(instance, cls)
instance.class = cls
instance:ctor(...)
return instance
end
cls.create = function(_, ...)
return cls.new(...)
end return cls
end
Lua-面向对象中类的构造的更多相关文章
- Lua面向对象----类、继承、多继承、单例的实现
(本文转载)学习之用,侵权立删! 原文地址 http://blog.csdn.net/y_23k_bug/article/details/19965877?utm_source=tuicool&a ...
- lua面向对象实现(实例化对象、继承、多态、多继承、单例模式)
lua面向对象实现: 一个类就像是一个创建对象的模具.有些面向对象语言提供了类的概念,在这些语言中每个对象都是某个特定类的实例.lua则没有类的概念,每个对象只能自定义行为和形态.不过,要在lua中模 ...
- Step By Step(Lua面向对象)
Step By Step(Lua面向对象) Lua中的table就是一种对象,但是如果直接使用仍然会存在大量的问题,见如下代码: 1 Account = {balance = 0}2 function ...
- BUAA面向对象设计与构造——第二单元总结
BUAA面向对象设计与构造——第二单元总结 第一阶段:单部傻瓜电梯的调度 第二阶段:单部可捎带电梯的调度 (由于我第一次写的作业就是可捎带模式,第二次只是增加了负数楼层,修改了一部分参数,因此一起总结 ...
- BUAA面向对象设计与构造——第一单元总结
BUAA面向对象设计与构造——第一单元总结 第一阶段:只支持一元多项式的表达式求导 1. 程序结构 由于是第一次接触面向对象的编程,加之题目要求不算复杂,我在第一次作业中并没有很好利用面向对象的特点, ...
- Lua面向对象之三:其它一些尝试
1.尝试一:子类对象调用被覆盖了的父类函数 根据元表设置流程,我们只有将父类元表找到就能调用父类的方法了 ①在子类Circle中增加一个调用父类方法的函数 --调用父类被子类覆盖了的name方法 fu ...
- Lua面向对象之二:类继承
1.类继承 ①代码 Sharp = { } --① 父类 function Sharp:new() local new_sharp = { } self.__index = self --②,self ...
- Lua面向对象之一:简单例子
1.Lua面向对象实现步骤 ①创建一个全局表(称之为元表) ②设置这个元表的__index值(值通常为元表自己,这样就能通过__index查找到对应的属性和方法) __index 赋值其实是一个fun ...
- lua面向对象封装
lua面向对象的一个封装,直接贴代码 --swfclass = {};local cs = {};function _class( child, base, ... )-- _.s( child ...
- 面向对象设计与构造:oo课程总结
面向对象设计与构造:OO课程总结 第一部分:UML单元架构设计 第一次作业 UML图 MyUmlInteraction类实现接口方法,ClassUnit和InterfaceUnit管理UML图中的类和 ...
随机推荐
- MVVM架构~目录
回到占占推荐博客索引 MVVM在概念上是真正将页面与数据逻辑分离的模式,在开发方式上,它是真正将前台代码开发者(JS+HTML)与后台代码开发者分离的模式(asp,asp.net,php,jsp).在 ...
- Android 透明度百分比对应的 十六进制
Android 透明度百分比对应的 十六进制 先把结果放在这里,方便大家查询,也方便自己,UI太喜欢用百分比表示了=.=! 透明度百分比对应的十六进制: (说明:百分比计算出来会有小数,按照常规的四舍 ...
- Distributed2:Linked Server Login 添加和删除
一,通过 sys.sp_addlinkedsrvlogin 创建Linked Server的Login 当在local Server 上需要访问Linked Server时,Local Server ...
- The transaction log for database 'tempdb' is full due to 'ACTIVE_TRANSACTION'
今天早上,Dev跟我说,执行query statement时出现一个error,detail info是: “The transaction log for database 'tempdb' is ...
- 利用Bootstrap快速搭建个人响应式主页(附演示+源码)
1.前言 我们每个程序员都渴望搭建自己的技术博客平台与他人进行交流分享,但使用别人的博客模板没有创意.做网站后台的开发人员可能了解前端,可是自己写一个不错的前端还是很费事的.幸好我们有Bootstra ...
- Sql Server系列:数据库组成及系统数据库
1. 数据库组成 数据库的存储结构分为逻辑存储结构和物理存储结构. ◊ 逻辑存储结构:说明数据库是由哪些性质的信息所组成.SQL Server的数据库不仅仅只是数据的存储,所有与数据处理操作相关的信息 ...
- Windows Phone 8弹窗
新建一个UserControl,添加到相应位置 <Grid x:Name="LayoutRoot" Background="{StaticResource Phon ...
- 《JS设计模式笔记》 4,桥接模式
//桥接模式的作用在于将实现部分和抽象部分分离开来,以便两者可以独立的变化. var singleton=function(fn){ var result; return function(){ re ...
- JavaScript 开发技巧 || 返回有效值
<script type="text/javascript">var objOne = undefined || "" || null || 1 | ...
- ASP.NET MVC5 网站开发实践(二) Member区域 - 用户部分(3)修改资料、修改密码
在上一篇博客中实现了用户的注销和登录,其实代码里落了点东西,就是用户登录要更新最后一次登录时间和登录IP,这次补上.今天做修改资料和修改密码,TryUpdateModel是新用到的东西. 目录: AS ...