要理解lua的class,首先要先理解metatable
的作用和__index
以及lua调用table里面的函数的时候搜索函数的逻辑:
1、直接当前表里面搜索函数 如果存在,直接调用,不存在继续
2、如果表里面不存在调用的函数,会查找表的metatable的__index
a、如果__index是一个表,则在该表里面查找,回到第一步
b、如果__index是一个函数,则传递要查找的表、函数名字给__index这个函数,并返回函数的返回结果。如果函数返回一个函数则执行该函数,或者直接提示找不到函数,或者返回另外一个表,则又回到第一步在这个表里面查找
伪代码如下:
"index": The indexing access table[key].
function gettable_event (table,key)
local h
if type(table) == "table" then
local v = rawget(table,key)
if v ~= nil then return v end
h = metatable(table).__index
if h == nil then return nil end
else
h = metatable(table).__index
if h == nil then
error(···)
end
end
if type(h) == "function" then
return (h(table,key))
else return h[key]
end
end
cocos2dx-lua
的class实现
下面来看看cocos2dx
的lua的class的实现方式
class的声明
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 --如果参数是一个函数 则将这个函数设置为类的__create函数 assert(cls.__create == nil,string.format("class() - create class "%s" with more than one creating function",classname));
cls.__create = super
elseif superType == "table” then --如果是一个表 if super[".isclass"] then --如果是一个c++的对象 -- 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
cls.__supers = cls.__supers or {}
cls.__supers[#cls.__supers + 1] = super
if not cls.super then
cls.super = super
end
end
else
error(string.format("class() - create class "%s" with invalid super type",classname),0)
end
end
cls.__index = cls
if not cls.__supers or #cls.__supers == 1 then
setmetatable(cls,{__index = cls.super})
else
setmetatable(cls,{__index = function(_,key)
local supers = cls.__supers
for i = 1,#supers do
local super = supers[i]
if super[key] then return super[key] end
end
end})
end
if not cls.ctor then
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
函数里面用到的setmetatableindex的实现
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_
这里有两种情况:
关于C++类搜索key的猜测和测试
对于a的问题,目前猜测是这样,因为metatable的__index是一个函数,所以我猜测是这个函数做了一些特殊操作,因此进行了如下实验:
因为我们知道当在一个表或者userdata中找不到某个域的时候,回去__index中查找,如果还是__index是一个函数,则传入__index的参数是这个userdata或者表本身和要查找的域的名字,所以我们考虑设置__index函数为如下的函数:
function myindex(t,key)
return getmetatable(t)[key]
end
这样就告诉表或者userdata,如果找不到某个函数,就将自己和key传递个__index然后从自己的metatable中查找。实验如下:
local Class1 = {}
function Class1:test()
print('test')
end
local Class2 = {}
local myIndex = function(t,key)
return getmetatable(t)[key]
end
Class1.__index = myIndex
function Class2:new()
local o = {}
local t = {__index = myIndex}
setmetatable(o,t)
local t1 = {__index = myIndex}
setmetatable(t,t1)
setmetatable(t1,Class1)
return o
end
local ta = Class2.new()
ta:test()
这段代码输出为test,也就是说可以调用到Class1的test函数
上面的代码Class1就只是o
的metatable
的metatable
的metatable
,和我们cocos2dx返回的userdata的结构类似了
我们来看看这段代码是如何做到的:
- 首先Class1有一个test函数
- 然后Class2只是为了给new一个作用域,主要看new的代码
- 新建一个表o
- 设置o的metatable为t,t的__index为上面说到的函数
- 然后设置t的为metable为t1,t1的__index也为上面的函数
- 最后设置t1的metatable为Class1,Class1的__index也是myIndex
来看调用关系
- 在ta中查找,找不到,继续
- ta中没有通过ta的metatable(t)的__index查找,__index为函数,则将ta和’test’作为参数传递给该函数,该函数通过getmetatable(ta)即(t)查找,t中也没有,继续
- t中没有,通过t的metatable(t1)的__index查找,也为函数,将t和’test’作为参数传递给函数,通过getmetatable(t)即(t1)中查找,t1中也没有,继续
- t1中没有,通过t1的metatable(Class1)的__index查找,为函数,将t1和’test’作为参数传递给函数,通过getmetatable(t1)即(Class1)查找,找到,所以返回Class1的test函数
说明这种实现方式是可行的,那么再来看看cocos2dx是否是这样实现的。
通过创建一个派生自cocos2dx
的一个userdata
test
,然后尝试输出下面的函数
print(getmetatable(test).__index(test,"visit”))
输出为函数,说明找到了函数,然后我们尝试重载一个函数来看看。
local tmpmetatablefunc = getmetatable
getmetatable = function(ta)
print(ta)
return tmpmetatablefunc(ta)
end
function ViewBase:setPosition(x,y)
print("--------")
local tmpindex = getmetatable(self).__index
getmetatable(self).__index = function(t1,key) print(t1,key) return tmpindex(t1,key) end
local a = getmetatable(self).__index(self,'setPosition')
print(a)
local b = getmetatable(self)['setPosition']
print("ttttttttttt")
print(a == b)
print("callfunction")
a(self,x,y)
print("viewbase.setPosition")
end
通过__index来获取setPosition函数
当ViewBase重新定一个setPosition函数的时候,如果用这种方式来重载的时候,我发现出现了递归调用,通过上面的测试代码发现是因为通过__index查找到的函数就是我们在这里定义的ViewBase:setPosition本身,而不是我们想调用的其基类的setPosition。由此还可以推断出另外一个事实,那就是tolua++中__index并不是仅仅搜索metatable,还是对tolua.getpeer进行搜索,因为通过上面的Class的定义我们知道ViewBase是放在tolua.getpeer的表的metatale的__index中的。但是这里还没有证明__index会搜索getmetatable的key。
这里我们修改一下函数的名字
local tmpmetatablefunc = getmetatable
getmetatable = function(ta)
print(ta)
return tmpmetatablefunc(ta)
end
function ViewBase:setPosition1(x,y)
print("viewbase.setPosition")
end
我们重新定义的函数叫setPosition1,这样搜索的时候就不会在tolua.getpeer中找到setPosition了。然后调用setPosition1来设置位置,发现成功了,那就证明
__index函数确实会搜索metatable的域了。
并且综合上面的分析,还可以知道其搜索顺序是先搜索tolua.getpeer中的函数,再搜索metatable,这样就可以做到优先使用我们重新定义的函数而不是积累的函数,做到重定义父类函数的功能。
这里分析了这么多,其实还不如直接去看tolua++的源代码,不过因为时间有限,对lua的c接口还不熟悉,所以仅先通过在lua这边看到的现象进行一些分析知其然,以后再仇视时间区看看tolua++代码和lua代码,之其所以然吧。
对于C++类的派生,创建的时候其实是先从C++创建一个原始的userdata,然后通过设置其getpeer的metatable来扩展其成员函数
其搜索顺序应该是先b后a
如果访问的是C++的原生函数,则是从getmetatable获取到,如果是派生出来的函数,则通过tolua.getpeer的表来得到其类或者父类的域
这个时候其函数和成员变量都来自于
instance[funcname] ——————>instance自身以及其metatable的__index域(递归)
这里是直接创建一个表,然后将其metatable指向其类,然后在访问instance的域的时候就会找到其类或者父类的域了
而如果要调用父类的函数而不是调用自己重载的函数,可以使用如下函数:
function getBaseFunc(data,name)
local a
if data.super ~= nil then
a = data.super[a]
end
if a == nil then
a = getmetatable(data)[a]
end
return a
end
如果调用指定级数的函数
可以直接使用ClassName.func(self,param)
cocos2dx搜索key的实现
cocos2dx中实现了__index函数, 代码如下:
- tolua_usertype 创建一个metatable且命名,这个metatable就代表了一个C++的
/* Register a usertype
* It creates the correspoding metatable in the registry,for both 'type' and 'const type'.
* It maps 'const type' as being also a 'type'
*/
TOLUA_API void tolua_usertype (lua_State* L,const char* type)
{
char ctype[128] = "const ";
strncat(ctype,type,120);
/* create both metatables */
if (tolua_newmetatable(L,ctype) && tolua_newmetatable(L,type))
mapsuper(L,ctype); /* 'type' is also a 'const type' */
}
在这个函数中调用了tolua_newmetatable
函数
2. tolua_newmetatable 创建metatable
static int tolua_newmetatable (lua_State* L,const char* name)
{
int r = luaL_newmetatable(L,name);
#ifdef LUA_VERSION_NUM /* only lua 5.1 */
if (r) {
lua_pushvalue(L,-1);
lua_pushstring(L,name);
lua_settable(L,LUA_REGISTRYINDEX);
};
#endif
if (r)
tolua_classevents(L);
lua_pop(L,1);
return r;
}
这个函数中就调用了tolua_classevent来设置metatable的__index函数等metafunction
3. tolua_classevents 设置么他function,其中就包括__index函数
/* Register class events
* It expects the metatable on the top of the stack
*/
TOLUA_API void tolua_classevents (lua_State* L)
{
lua_pushstring(L,"__index")
lua_pushcfunction(L,class_index_event)
lua_rawset(L,-3)
lua_pushstring(L,"__newindex")
lua_pushcfunction(L,class_newindex_event)
lua_rawset(L,-3)
lua_pushstring(L,"__add")
lua_pushcfunction(L,class_add_event)
lua_rawset(L,"__sub")
lua_pushcfunction(L,class_sub_event)
lua_rawset(L,"__mul")
lua_pushcfunction(L,class_mul_event)
lua_rawset(L,"__div")
lua_pushcfunction(L,class_div_event)
lua_rawset(L,"__lt")
lua_pushcfunction(L,class_lt_event)
lua_rawset(L,"__le")
lua_pushcfunction(L,class_le_event)
lua_rawset(L,"__eq")
lua_pushcfunction(L,class_eq_event)
lua_rawset(L,"__call")
lua_pushcfunction(L,class_call_event)
lua_rawset(L,"__gc")
lua_pushstring(L,"tolua_gc_event")
lua_rawget(L,LUA_REGISTRYINDEX)
/*lua_pushcfunction(L,class_gc_event)
lua_rawset(L,-3)
}
- class_index_event即为真正的搜索key的逻辑了
/* Class index function
* If the object is a userdata (ie,an object),it searches the field in
* the alternative table stored in the corresponding "ubox" table.
*/
static int class_index_event (lua_State* L)
{
int t = lua_type(L,1)
if (t == LUA_TUSERDATA) //如果是userdata
{
/* Access alternative table */
#ifdef LUA_VERSION_NUM /* new macro on version 5.1 */ //从peer里面搜索key
lua_getfenv(L,1)
if (!lua_rawequal(L,-1,TOLUA_NOPEER)) {
lua_pushvalue(L,2)
lua_gettable(L,-2)
if (!lua_isnil(L,-1)) //如果搜索到key,则直接返回
return 1
}
#else
lua_pushstring(L,"tolua_peers")
lua_rawget(L,LUA_REGISTRYINDEX)
lua_pushvalue(L,1)
lua_rawget(L,-2)
if (lua_istable(L,-1))
{
lua_pushvalue(L,2)
lua_rawget(L,-2)
if (!lua_isnil(L,-1))
return 1
}
#endif
lua_settop(L,2)
/* Try metatables */
lua_pushvalue(L,1)
while (lua_getmetatable(L,-1))
{ /* stack: obj key obj mt */
lua_remove(L,-2)
if (lua_isnumber(L,2)) /* check if key is a numeric value */
{
/* try operator[] */
lua_pushstring(L,".geti")
lua_rawget(L,-2)
if (lua_isfunction(L,-1))
{
lua_pushvalue(L,1)
lua_pushvalue(L,2)
lua_call(L,2,1)
return 1
}
}
else
{ //在metatable中搜索
lua_pushvalue(L,2)
lua_rawget(L,-2)
if (!lua_isnil(L,-1))
return 1
else
lua_pop(L,1)
/* try C/C++ variable */
lua_pushstring(L,".get")
lua_rawget(L,-2)
if (lua_istable(L,2)
lua_rawget(L,-2)
if (lua_iscfunction(L,-1))
{
lua_pushvalue(L,1)
lua_pushvalue(L,2)
lua_call(L,1)
return 1
}
else if (lua_istable(L,-1))
{
/* deal with array: create table to be returned and cache it in ubox */
void* u = *((void**)lua_touserdata(L,1))
lua_newtable(L)
lua_pushstring(L,".self")
lua_pushlightuserdata(L,u)
lua_rawset(L,-3)
lua_insert(L,-2)
lua_setmetatable(L,-2)
lua_pushvalue(L,-1)
lua_pushvalue(L,2)
lua_insert(L,-2)
storeatubox(L,1)
return 1
}
}
}
lua_settop(L,3)
}
lua_pushnil(L)
return 1
}
else if (t== LUA_TTABLE) //如果是表
{
lua_pushvalue(L,1)
class_table_get_index(L)
return 1
}
lua_pushnil(L)
return 1
}
class_table_get_index 函数
static int class_table_get_index (lua_State* L)
{
// stack: obj key ... obj
while (lua_getmetatable(L,-1)) { /* stack: obj key obj mt */
lua_remove(L,-2); /* stack: ... mt */
lua_pushvalue(L,2); /* stack: ... mt key */
lua_rawget(L,-2); /* stack: ... mt value */
if (!lua_isnil(L,-1)) {
return 1;
} else {
lua_pop(L,1);
}
/* try C/C++ variable */
lua_pushstring(L,".get");
lua_rawget(L,-2); /* stack: obj key ... mt tget */
if (lua_istable(L,-1)) {
lua_pushvalue(L,2); /* stack: obj key ... mt tget key */
lua_rawget(L,-2); /* stack: obj key ... mt tget value */
if (lua_iscfunction(L,-1)) {
lua_call(L,0,1);
return 1;
} else if (lua_istable(L,-1)) {
return 1;
}
lua_pop(L,2);
}
}
lua_pushnil(L);
return 1;
}