在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键中查找。

查找一个表元素的规则如下:

1.在表中查找,如果找到,返回该元素;如果找不到,继续2
2.判断该表是否有元表,如果没有,返回nil;如果有,继续3
3.判断元表中是否有__index方法,
如果__index方法为nil,返回nil;
如果__index方法是一个表,则重复 1,2,3;
如果__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-面向对象中类的构造的更多相关文章

  1. Lua面向对象----类、继承、多继承、单例的实现

    (本文转载)学习之用,侵权立删! 原文地址   http://blog.csdn.net/y_23k_bug/article/details/19965877?utm_source=tuicool&a ...

  2. lua面向对象实现(实例化对象、继承、多态、多继承、单例模式)

    lua面向对象实现: 一个类就像是一个创建对象的模具.有些面向对象语言提供了类的概念,在这些语言中每个对象都是某个特定类的实例.lua则没有类的概念,每个对象只能自定义行为和形态.不过,要在lua中模 ...

  3. Step By Step(Lua面向对象)

    Step By Step(Lua面向对象) Lua中的table就是一种对象,但是如果直接使用仍然会存在大量的问题,见如下代码: 1 Account = {balance = 0}2 function ...

  4. BUAA面向对象设计与构造——第二单元总结

    BUAA面向对象设计与构造——第二单元总结 第一阶段:单部傻瓜电梯的调度 第二阶段:单部可捎带电梯的调度 (由于我第一次写的作业就是可捎带模式,第二次只是增加了负数楼层,修改了一部分参数,因此一起总结 ...

  5. BUAA面向对象设计与构造——第一单元总结

    BUAA面向对象设计与构造——第一单元总结 第一阶段:只支持一元多项式的表达式求导 1. 程序结构 由于是第一次接触面向对象的编程,加之题目要求不算复杂,我在第一次作业中并没有很好利用面向对象的特点, ...

  6. Lua面向对象之三:其它一些尝试

    1.尝试一:子类对象调用被覆盖了的父类函数 根据元表设置流程,我们只有将父类元表找到就能调用父类的方法了 ①在子类Circle中增加一个调用父类方法的函数 --调用父类被子类覆盖了的name方法 fu ...

  7. Lua面向对象之二:类继承

    1.类继承 ①代码 Sharp = { } --① 父类 function Sharp:new() local new_sharp = { } self.__index = self --②,self ...

  8. Lua面向对象之一:简单例子

    1.Lua面向对象实现步骤 ①创建一个全局表(称之为元表) ②设置这个元表的__index值(值通常为元表自己,这样就能通过__index查找到对应的属性和方法) __index 赋值其实是一个fun ...

  9. lua面向对象封装

    lua面向对象的一个封装,直接贴代码 --swfclass = {};local cs = {};function _class( child, base, ... )--    _.s( child ...

  10. 面向对象设计与构造:oo课程总结

    面向对象设计与构造:OO课程总结 第一部分:UML单元架构设计 第一次作业 UML图 MyUmlInteraction类实现接口方法,ClassUnit和InterfaceUnit管理UML图中的类和 ...

随机推荐

  1. .net基础复习之一

    一.             ADO 与ADO.NET两种数据访问方式区别? 1. ADO与ADO.NET简介ADO与ADO.NET既有相似也有区别,他们都能够编写对数据库服务器中的数据进行访问和操作 ...

  2. CSS3新特性,绘制常见图形

    前言:最近准备做一个自己的网页,设计稿中导航我准备设计成矩形,也有hover样式展示的矩形,当中一些头像等等.以前除了画圆,好像真没认真画过其他图形,今天就画画我们常见到的几个图形. 在此之前我们有必 ...

  3. Utility3:Understand Dashboard Report

    To see data in the SQL Server Utility dashboard, select the top node in the Utility Explorer tree - ...

  4. SQL Server 解读【已分区索引的特殊指导原则】(3) - 非聚集索引分区

    一.前言 在MSDN上看到一篇关于SQL Server 表分区的文档:已分区索引的特殊指导原则,如果你对表分区没有实战经验的话是比较难理解文档里面描述的意思.这里我就里面的一些概念进行讲解,方便大家的 ...

  5. HTML5系列:HTML5本地存储

    1. Web Storage存储 HTML4在客户端存储数据通常使用Cookie存储机制将数据保存在用户的客户端,但使用Cookie方式存储客户端数据存在一系列的制约发展因素,如限制存储数据空间大小. ...

  6. Winform 生成不需要安装的exe可执行文件 ILMerge使用

    今天应领导要求,把一个程序打包生成一个可以执行的exe文件,不是安装包那种,类似于绿色文件,就是一个exe,可以直接运行.上网查了一下有一个工具可以实现ILMerge. 参照两个文档http://bl ...

  7. 引用类型-Object类型

    创建Object实例的方式有两种. 第一种是使用new操作符后跟Object构造函数 var person = new Object(); person.name = "liao" ...

  8. 使用Ubuntu 12.04作为日常电脑环境

    搜狗输入法出来之后,我觉得有必要写一篇博客说明一下,如何使用Ubuntu作为日常的电脑系统.我使用的Ubuntu版本是12.04,没有使用Ubuntukylin,因为的电脑比较老,使用那个版本,电脑有 ...

  9. (转)J2EE的13种核心技术

    一.JDBC(Java Database Connectivity)  JDBC API为访问不同的数据库提供了一种统一的途径,象ODBC一样,JDBC对开发者屏蔽了一些细节问题,另外,JDBC对数据 ...

  10. jdk线程池主要原理

    本文转自:http://blog.csdn.net/linchengzhi/article/details/7567397 正常创建一个线程的时候,我们是这样的:new thread(Runnable ...