本文将为您提供关于cocos2dx-lua里面class的实现的一些问题记录和思考的详细介绍,我们还将为您解释cocosluajs的相关知识,同时,我们还将为您提供关于关于cocos2dx接Andro
本文将为您提供关于cocos2dx-lua里面class的实现的一些问题记录和思考的详细介绍,我们还将为您解释cocos lua js的相关知识,同时,我们还将为您提供关于
- cocos2dx-lua里面class的实现的一些问题记录和思考(cocos lua js)
关于cocos2dx接Android sdk的一些坑 - cocos2d lua 工作遇到的一些问题(不定时更新)
- Cocos2d-x 3.9 + VS2012 + BabeLua 如何搭建cocos2dx lua环境
- cocos2d-x lua 屏幕适配问题(OpenGL调用),版本号(cocos2dx v3.4)
cocos2dx-lua里面class的实现的一些问题记录和思考(cocos lua js)
首先要理解lua的class,要先理解Metatable的作用和__index以及lua调用table里面的函数的时候搜索函数的逻辑:
1、直接当前表里面搜索函数 如果存在,直接调用,不存在继续
2、如果表里面不存在调用的函数,会查找表的Metatable的__index
a、如果__index是一个表,则在该表里面查找,回到第一步
b、如果__index是一个函数,则传递要查找的表、和函数名字给__index这个函数,如果函数返回一个函数则执行该函数,或者直接提示找不到函数,或者返回另外一个表,则又回到第一步在这个表里面查找
下面来看看cocos的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));
-- if super is function,set it to __create
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 __create函数就等于调用c++类的create函数
else
-- super is pure lua class
cls.__supers = cls.__supers or {} 设置
cls.__supers[#cls.__supers + 1] = 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),0)
end
end
cls.__index = cls
if not cls.__supers or #cls.__supers == 1 then 如果只有一个父类 则设置Metatable为一个表
setMetatable(cls,{__index = cls.super})
else
setMetatable(cls,{__index = function(_,key) 如果有多个父类,则设置Metatable为一个函数,通过函数查找对应的函数
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
-- 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
函数里面用到的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) 另外总觉得这一句有问题,不是应该是setMetatableindex(mt.__index,index)吗,如果__index是函数,也应该扩展让其会搜索其Metatable或者自身之后,再使用setMetatableindex(mt,index),才会生效,请大神指点迷津
end
end
end
setMetatableindex = setMetatableindex_
这里有两种情况:
对于从C++对象派生的情况,new出来的实际上并不是一个table而是一个userdata
这个时候其函数从两个地方来:
a、getMetatable(instance)[funcname]——————>来自于C++类和C++类的父类
这里有一个不解的地方是这个所有的函数都位于Metatable中而不是Metatable的__index域中,是怎么做到从Metatable中查找域而不是Metatable的__index域呢。通过输出可以看到每一个Metatable中其实是有__index域的,并且是一个函数,不过没有找到实现
b、tolua.getpeer(instance)[funcname]——————>来自于getpeer返回的table以及其Metatable的__index域(递归)
而对于从纯lua对象派生的类,new出来的实例也是一个table
对于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
来看调用关系
1、在ta中查找,找不到,继续
2、ta中没有通过ta的Metatable(t)的__index查找,__index为函数,则将ta和’test'作为参数传递给该函数,该函数通过getMetatable(ta)即(t)查找,t中也没有,继续
3、t中没有,通过t的Metatable(t1)的__index查找,也为函数,将t和’test'作为参数传递给函数,通过getMetatable(t)即(t1)中查找,t1中也没有,继续
4、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)
--getMetatable(self)['setPosition'](self,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("--------")
local tmpindex = getMetatable(self).__index
getMetatable(self).__index = function(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,y)
--getMetatable(self)['setPosition'](self,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接Android sdk的一些坑
简单说说UI线程 :在Android中,有个非常重要的家伙非常霸道,那就是UI线程。这霸道之一:不能被阻塞。 之二:系统对每一个组件的调用都从UI线程分发出去。
简单说说openGL线程:但凡cocos2dx 启动的绘制线程都是openGL线程。就这么多
任何SDK界面的调用,必须从UI线程中调用,所以需要放到主线程中。如果我们直接从GL线程中调用,轻则调用不了,重者程序蹦死。
解决办法:
得到主线程的handler,这里简单说一种,就是在onCreate中new一个静态handler。
或者new Handler(Looper.getMainLooper()),且叫mainHandler吧,
启动一个线程,
Thread sendThread=new Thread(new Runnable(){ public void run() { mainHandler.post(sendRun); } });
public Runnable sendRun=new Runnable() { @Override public void run() { // //这里就可以调用sdk里面的东西了
} };
</pre><pre name="code"><span>如何从UI线程中调用OpenGL线程呢,直接调用,我以前也干过,感觉没什么问题被发现(he he),如果发现了问题我觉得还是这么调用的好</span>
</pre><pre name="code">Cocos2dxGLSurfaceView.getInstance().queueEvent(new Runnable() { public void run() { <span> </span>//回调什么马的 } });至于想知道,jni native什么的 还请出门右拐,不送
cocos2d lua 工作遇到的一些问题(不定时更新)
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.
原因:不要用Node去运行Animate,要用Sprite。游戏中实时替换新的sprite资源: Sprite: setSpriteFrame(cc.Sprite:create(“新资源”):getSpriteFrame());
Cocos2d-x 3.9 + VS2012 + BabeLua 如何搭建cocos2dx lua环境
这几天一直在试一些cocos2dx lua的开发环境,试过cocos code ide 1.2和cocos code ide 2.0。前者莫名其妙软件崩 溃,后者却不支持lua的自动补齐和代码提示,只能回归vs2012了。 本文就默认大家都下好了cocos2d-x3.9,其实cocos2d-x3.x都差不多,稍微有点区别。也默认大家都装好了BabeLua。我的 BabeLua不是1.x版本的,是3.x版本的。
我的BabeLua安装好后,会在VS2012控制面板出现一个Lua按钮,点击按钮后没有网上其他教程说的Lua Setting,这个没有 关系。
下面开始搭建环境: 1.进入到cocos2dx3.9 源码包的tools/cocos2d-console/bin目录下,使用cocos new 项目名称 -p com.cocos.game -l lua -d 工程目录 这种方式来创建cocos2dxlua 项目。创建好的项目目录是这样的(我的项目名称是HelloLua003):
2.用VS2012打开刚刚创建的项目,注意入口是在frameworks/runtime-src/proj.win32
点击编译运行,会将之前的项目目录更新成如下所示:
新生成的simulator目录下有我们需要使用的模拟器HelloLua003.exe文件,这个在配置lua环境需要用到。 3.点击VS2012上方的Lua按钮,选择new lua project,配置好后如下图所示:
下面对每个选择进行详细介绍 Lua Project Lua scripts folder:选择Lua文件的保存位置,一般是src Lua exe path:选择模拟器的位置,在simulator/win32下面的.exe文件 注意,在选择完Lua exe path 后会自动生成下面的Working path,默认是生成的simulator/win32,这个是错误的,改成 自己的项目目录 Working path:工程目录,比如我的是E:\cocos2dx_proj\cocos2d_proj\cocos2dx_3.9_Lua_proj\HelloLua003 Command line:输入-workdir 项目目录 -file src\main.lua,比如我的是-workdir E:\cocos2dx_proj\ cocos2d_proj\cocos2dx_3.9_Lua_proj\HelloLua003 -file src\main.lua Lua project name:可以随意自己定,比如我就直接写的Lua 4.点击确认后会在vs上生成Lua工程目录
6.将Lua设置为启动项后点击运行,得到如下界面表示成功。
当然,我推荐使用sublime text2 来写代码,写好代码会自动同步到vs当中,然后使用vs编译查看效果。具体的sublime text2 配置cocos2dx lua api 环境,可以自行百度,网上教程很多。
cocos2d-x lua 屏幕适配问题(OpenGL调用),版本号(cocos2dx v3.4)
前言
我们知道,cocos2dx 中屏幕适配的设置方法是
Director::getInstance()->getopenGLView()->setDesignResolutionSize(960,640,kResolutionShowAll);
为了保持我们的游戏不被拉伸,选择showAll方法。但是有一个问题,showAll会留黑边,那么我们只需要在openGL中渲染黑边即可。这样黑边就会被填充为我们自己设置的图片。话不多说,看看下面的代码。
MainScene.lua
调用示例如下,只需要在onEnter里面渲染即可
function MainScene:onEnter() local function createSpriteWithPathPosScale(path,pos,scale) -- body local sprite = cc.Sprite:create(path) sprite : setAnchorPoint(cc.p(0,0)) sprite : setPosition(pos) sprite : setScale(scale) return sprite end local layer = cp.ScreenMatchLayer : create() layer:retain() local sprite = createSpriteWithPathPosScale("ui_img_left.jpg",cc.p(0 - 88,0),1) layer : getChildByName("_node") : addChild(sprite) sprite = createSpriteWithPathPosScale("ui_img_left.jpg",cc.p(960,-1) layer : getChildByName("_node") : addChild(sprite) sprite = createSpriteWithPathPosScale("ui_img_top.jpg",cc.p(480,640 + 32.5),1) layer : getChildByName("_node") : addChild(sprite) sprite = createSpriteWithPathPosScale("ui_img_top.jpg",-480-32.5),-1) layer : getChildByName("_node") : addChild(sprite) end
AppDelegate.cpp
这里面对ScreenMatchLayer进行注册以便被lua调用
bool AppDelegate::applicationDidFinishLaunching() { // set default FPS Director::getInstance()->setAnimationInterval(1.0 / 60.0f); // register lua module auto engine = LuaEngine::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(engine); lua_State* L = engine->getLuaStack()->getLuaState(); lua_module_register(L); ScreenMatchLayer::lua_bind_AllFunction(L); // If you want to use Quick-Cocos2d-X,please uncomment below code // register_all_quick_manual(L); LuaStack* stack = engine->getLuaStack(); stack->setXXTEAKeyAndSign("2dxLua",strlen("2dxLua"),"XXTEA",strlen("XXTEA")); //register custom function //LuaStack* stack = engine->getLuaStack(); //register_custom_function(stack->getLuaState()); #if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0) // NOTE:Please don't remove this call if you want to debug with Cocos Code IDE RuntimeEngine::getInstance()->start(); cocos2d::log("iShow!"); #else if (engine->executeScriptFile("src/main.lua")) { return false; } #endif return true; }
ScreenMatchLayer.h
#ifndef __SCREENMATCHLAYER_H__ #define __SCREENMATCHLAYER_H__ #include "cocos2d.h" namespace cocos2d{ class ScreenMatchLayer : public Layer { public: ScreenMatchLayer(void); ~ScreenMatchLayer(void); static ScreenMatchLayer* create(); bool init(); void visit(Renderer *renderer,const Mat4& parentTransform,uint32_t parentFlags); void onBeforeVisit(); void onAfterVisit(); static int lua_bind_AllFunction(lua_State* tolua_S); static const std::string classprefix; static const std::string fullName; static const std::string className; private: Node* _node; CustomCommand _beforeVisit; CustomCommand _afterVisit; }; } int lua_cocos2dx_ScreenMatchLayer_create(lua_State* tolua_S); #endif
ScreenMatchLayer.cpp
#include "ScreenMatchLayer.h" #include "tolua_fix.h" #include "LuaBasicConversions.h" using namespace cocos2d; const std::string ScreenMatchLayer::classprefix = "cp"; const std::string ScreenMatchLayer::className = "ScreenMatchLayer"; const std::string ScreenMatchLayer::fullName = classprefix + "." + className; ScreenMatchLayer::ScreenMatchLayer(void) { } ScreenMatchLayer::~ScreenMatchLayer(void) { } bool ScreenMatchLayer::init() { if ( !Layer::init() ) { return false; } _node = Node::create(); _node->setName("_node"); _node->setAnchorPoint(ccp(0,0)); addChild(_node); GLView* openGLView = this->_director->getopenGLView(); Size frameSize = openGLView->getFrameSize(); Size designSize = Size(960,640); Size nodeSize = Size(0,0); bool frameSizeWidthLarger = (designSize.width / designSize.height) < (frameSize.width / frameSize.height ); if(frameSizeWidthLarger) { nodeSize.height = designSize.height; nodeSize.width = nodeSize.height * (frameSize.width / frameSize.height); } else { nodeSize.width = designSize.width; nodeSize.height = nodeSize.width * (frameSize.height / frameSize.width); } _node->setPosition(ccp((nodeSize.width - designSize.width) / 2,(nodeSize.height - designSize.height) / 2)); auto _afterDrawListener = EventListenerCustom::create(Director::EVENT_AFTER_VISIT,[this](EventCustom* event) { this->visit(this->_director->getRenderer(),Mat4::IDENTITY,0); }); auto eventdispatcher = Director::getInstance()->getEventdispatcher(); eventdispatcher->addEventListenerWithFixedPriority(_afterDrawListener,1); return true; } void ScreenMatchLayer::onBeforeVisit() { GLView* openGLView = this->_director->getopenGLView(); Size frameSize = openGLView->getFrameSize(); glViewport((GLint)(0),(GLint)(0),(GLsizei)(frameSize.width),(GLsizei)(frameSize.height)); } void ScreenMatchLayer::onAfterVisit() { GLView* openGLView = this->_director->getopenGLView(); Size designSize = openGLView->getDesignResolutionSize(); openGLView->setViewPortInPoints(0,designSize.width,designSize.height); } void ScreenMatchLayer::visit(Renderer *renderer,uint32_t parentFlags) { if(!_visible) return; _beforeVisit.init(_globalZOrder); _beforeVisit.func = CC_CALLBACK_0(ScreenMatchLayer::onBeforeVisit,this); renderer->addCommand(&_beforeVisit); Node::visit(renderer,parentTransform,parentFlags); _afterVisit.init(_globalZOrder); _afterVisit.func = CC_CALLBACK_0(ScreenMatchLayer::onAfterVisit,this); renderer->addCommand(&_afterVisit); } ScreenMatchLayer * ScreenMatchLayer::create() { ScreenMatchLayer *pRet = new ScreenMatchLayer(); if ( pRet && pRet->init() ) { pRet->autorelease(); return pRet; } CC_SAFE_DELETE(pRet); return nullptr; } int ScreenMatchLayer::lua_bind_AllFunction(lua_State* tolua_S) { lua_getglobal(tolua_S,"_G"); if (lua_istable(tolua_S,-1))//stack:...,_G,{ tolua_open(tolua_S); tolua_module(tolua_S,classprefix.c_str(),0); tolua_beginmodule(tolua_S,classprefix.c_str()); tolua_usertype(tolua_S,ScreenMatchLayer::fullName.c_str()); tolua_cclass(tolua_S,className.c_str(),ScreenMatchLayer::fullName.c_str(),"cc.Layer",nullptr); tolua_beginmodule(tolua_S,className.c_str()); tolua_function(tolua_S,"create",lua_cocos2dx_ScreenMatchLayer_create); tolua_endmodule(tolua_S); g_luaType[typeid(ScreenMatchLayer).name()] = ScreenMatchLayer::fullName; g_typeCast[className] = ScreenMatchLayer::fullName; tolua_endmodule(tolua_S); } lua_pop(tolua_S,1); return 1; } int lua_cocos2dx_ScreenMatchLayer_create(lua_State* tolua_S) { int argc = 0; ScreenMatchLayer* parentOfFunction = nullptr; const std::string &functionString = "'lua_cocos2dx_ScreenMatchLayer_create'"; const std::string &luaFunctionString = ScreenMatchLayer::fullName + ":create"; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; if (!tolua_isusertable(tolua_S,1,&tolua_err)) { tolua_error(tolua_S,("#ferror in function " + functionString).c_str(),&tolua_err); return 0; } parentOfFunction = (ScreenMatchLayer*)tolua_tousertype(tolua_S,0); if (!parentOfFunction) { //tolua_error(tolua_S,("invalid 'cobj' in function " + functionString).c_str(),nullptr); //return 0; } #endif argc = lua_gettop(tolua_S) - 1; if (argc == 0) { ScreenMatchLayer* ret = ScreenMatchLayer::create(); object_to_luaval<ScreenMatchLayer>(tolua_S,(ScreenMatchLayer*)ret); return 1; } else {luaL_error(tolua_S,"%s has wrong number of arguments: %d,was expecting %d \n",luaFunctionString.c_str(),argc,1);} return 0; }
我们今天的关于cocos2dx-lua里面class的实现的一些问题记录和思考和cocos lua js的分享就到这里,谢谢您的阅读,如果想了解更多关于
本文标签: