当前位置: 移动技术网 > IT编程>脚本编程>Lua > Cocos2d-x中调用Lua及HelloWorld.lua源码分解

Cocos2d-x中调用Lua及HelloWorld.lua源码分解

2017年12月08日  | 移动技术网IT编程  | 我要评论

lua脚本,以前我不知道它有多强大,但是当我做了1年的手机网游之后,起码我发现了,更新客户端是一件很恐怖的事情(会导致大量玩家的流失,以及有一个漫长并且惊心动魄的审核过程),太扯了。于是,如果可以只更新脚本,那就不需要玩家重新下载客户端了,直接在线更新,嗯嗯,虽然我发现了这个,但是还没有实现。噗,代码写烂了,不好改。
 
所以啊,我已经做好准备了,如果下次用cocos2d-x开发,lua不可少啊~!
 
看看官方的例子吧,先来appdelegate.cpp的applicationdidfinishlaunching函数:

复制代码 代码如下:

#if (cc_target_platform == cc_platform_android)
    ccstring* pstrfilecontent = ccstring::createwithcontentsoffile("helloworld.lua ");
    if (pstrfilecontent)
    {
        pengine->executestring(pstrfilecontent->getcstring());
    }
#else
    std::string path = ccfileutils::sharedfileutils()->fullpathfromrelativepath("helloworld.lua");
    pengine->addsearchpath(path.substr(0, path.find_last_of("/")).c_str());
    pengine->executescriptfile(path.c_str());
#endif

是的,就看这一段就好了。就android加载lua脚本的方式有点奇怪,但是和luajava的加载方式很像(我喜欢,噗)。
也就是说,我们要执行某个lua脚本的话,就是用上面这段代码了,不解释,不好解释(难道要我解释源码?噗)。

来,看看helloworld.lua是怎么写的吧:

复制代码 代码如下:

local winsize = ccdirector:shareddirector():getwinsize()
local function createhellolayer()
    local layer = cclayer:create();
    local sprite = ccsprite:create("default.png");
    sprite:setposition(winsize.width / 2, winsize.height / 2);
    layer:addchild(sprite);
    return layer
end
local scene = ccscene:create();
scene:addchild(createhellolayer());
ccdirector:shareddirector():runwithscene(scene);

哎哎,lua的语法其实我也不是很熟悉,因为我真的没有用lua开发过。说说我懂的吧,注意几点:
1. 一般变量都要local xx形式,不要习惯了搞个int xx什么的哈
2.  lua是没有变量类型这个说法,你想它是什么类型,它就是什么类型,当然,赋值之后它的类型也就确定了
3.  然后,貌似cocos2d-x的lua要使用api的函数好简单啊,比如在cpp应该是
cclayer::create(),而到了lua这里就cclayer:create(),是的,注意一个是两个冒号,一个是一个冒号。
4. 使用方法是一个冒号,那使用属性呢?好像是,一个点。
5. 注意了,不管是静态方法,非静态方法,都是用一个冒号,在这里不存在“->”符号
 
好喇,大家又不是笨蛋,自己看看官方的hello.lua就能发现很多知识了。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网