?
?
我使用的cocos2d-x版本是2.3.3,先在一个C++工程中配置好lua的环境。
?
首先导入lua项目
1.liblua工程是cocos2d-x-2.2.3scriptingluaproj.win32liblua.vcxproj这个文件,导入VS2010工程中
2.包含目录:在工程的属性-配置属性-C/C++-常规-附加包含目录中加入$(ProjectDir)......scriptinglua olua,$(ProjectDir)......scriptinglualua,
$(ProjectDir)......scriptinglualua
3.在属性-配置属性-链接器-输入-附加依赖项加入liblua.lib和lua51.lib
好了,lua环境就配置好了
在HelloWorld.cpp中加入头文件引用#include CCLuaEngine.h,#include script_supportCCScriptSupport.h
下面开始写lua了,lua代码如下
?
pageName=equip
a={student=zhangsan,age=23}
function main()
print(leoooooooooooooo)
end
function printSomething(name,age)
print(-----------------name is ..name)
print(-----------------age is ..age)
end
function returnSomething(name,age)
return name,age
end
这个写的lua代码,下面看C++部分,首先在AppDelegate.cpp中加入
?
?
CCLuaEngine* pEngine = CCLuaEngine::defaultEngine();
CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);
来设置lua的引擎
?
然后在HelloWorld.cpp的点击事件中将lua代码加载
?
CCLuaEngine *pEngine = CCLuaEngine::defaultEngine();
pEngine->executeString(require lua/hello.lua);
下面主要说3个知识点
?
1.调用lua的函数
?
//调用无参数无返回值的函数
lua_State* L=pEngine->getLuaStack()->getLuaState();
//获得栈顶,并且保存值
int top=lua_gettop(L);
lua_getglobal(L,main);
//看看在不在那里
if(!lua_isfunction(L,-1))
{
CCLog(------------return);
}
//第一个参数是栈的状态的指针,第二个参数是参数个数,第三个参数是返回值的个数,第四个参数是出现错误的回调函数的地址
lua_pcall(L,0,0,0);
//还原栈
lua_settop(L,top);
//调用有参数,无返回值的函数
top=lua_gettop(L);
lua_getglobal(L,printSomething);
//看看在不在那里
if(!lua_isfunction(L,-1))
{
CCLog(------------return);
}
//一一对应啊
lua_pushstring(L,zhycheng);
lua_pushnumber(L,24);
lua_pcall(L,2,0,0);
lua_settop(L,top);
//调用有参数,有两个返回值的函数
top=lua_gettop(L);
lua_getglobal(L,returnSomething);
if(!lua_isfunction(L,-1))
{
CCLog(------------return);
}
lua_pushstring(L,new);
lua_pushnumber(L,22);
lua_pcall(L,2,2,0);
if(!lua_isnumber(L,-1)||!lua_isstring(L,-2))
{
CCLog(return error);
}
//name在下面
int age =(int)lua_tonumber(L,-1);
const char* name=lua_tostring(L,-2);
CCLog(age is %d,age);
CCLog(name %s,name);
lua_settop(L,top);
2.获得lua的一个全局变量的值
?
?
//读取lua的全局变量
top=lua_gettop(L);
lua_getglobal(L,pageName);
if(!lua_isstring(L,-1))
{
CCLog(return error);
}
const char* equipname=lua_tostring(L,-1);
CCLog(name is %s,equipname);
lua_settop(L,top);
3.访问全局table的某一个值
?
?
//获取lua表中的某个key的value
top=lua_gettop(L);
lua_getglobal(L,a);
if(!lua_istable(L,-1))
{
CCLog(error----------------);
}
lua_pushstring(L,student);
//lua_gettable是一个函数,它首先让键值出站,获取相应表元素的值,然后把这个值入栈
//此时student在-2的位子,然这个key出栈,让他的值入栈
lua_gettable(L,-2);
if(!lua_isstring(L,-1))
{
CCLog(error --------------);
}
const char* studentName = lua_tostring(L, -1);
CCLog(studentName is %s,studentName);
lua_settop(L,top);
//再获取的时候一定要注意栈的问题
//获取年龄
top=lua_gettop(L);
lua_getglobal(L,a);
if(!lua_istable(L,-1))
{
CCLog(error----------------);
}
lua_pushstring(L,age);
lua_gettable(L,-2);
if(!lua_isnumber(L,-1))
{
CCLog(error-----------------);
}
int aage=lua_tonumber(L,-1);
CCLog(aage is %d,aage);
lua_settop(L,top);
好了,就