cocos2dx之C++调用Lua

原文地址:http://blog.csdn.net/dingkun520wy/article/details/49839701

1.引入头文件

 

#include "cocos2d.h"
#include "CCLuaEngine.h"
USING_NS_CC;
using namespace std;
extern "C"{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

2导入Lua文件

如果是cocos2dx的Lua工程只需要在main.lua里面引用就可以了

cocos2dx之C++调用Lua

 

3.Lua文件编写

 

--Lua变量
strTemp = "乐逍遥"
--Lua的table
tableTemp = {name = "乐逍遥Jun", uuid = "001"}
--没有参数的函数
function test()
    return 100
end
--有参数的函数
function testadd(a,b,str)
    local c = a+b
    return c, str
end




4.C++中的调用

首先是找到AppDelegate.cpp中的

 

#if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT >0)

CC_CODE_IDE_DEBUG_SUPPORT的值改为0

如果是没有参数只有一个int返回值的Lua函数只需要调用cocos2dx封装好的executeGlobalFunction函数就行

 

auto engine = LuaEngine::getInstance();
engine->executeGlobalFunction("test");


如果是比较负责的函数

 

LuaStack * L =LuaEngine::getInstance()->getLuaStack();
    lua_State* tolua_s = L->getLuaState();
    
    //--------有参数和返回值的Lua函数的调用---------
    lua_getglobal(tolua_s, "testadd");    // 获取函数,压入栈中
    lua_pushnumber(tolua_s, 10);          // 压入第一个参数
    lua_pushnumber(tolua_s, 20);          // 压入第二个参数
    lua_pushstring(tolua_s, "测试");       // 压入第三个参数
    int iRet= lua_pcall(tolua_s, 3, 2, 0);// 调用函数,调用完成以后,会将返回值压入栈中,2表示参数个数,1表示返回结果个数。
    if (iRet)                       // 调用出错
    {
        const char *pErrorMsg = lua_tostring(tolua_s, -1);
        CCLOG("错误-------%s",pErrorMsg);
        return ;
    }
    int fValue = lua_tonumber(tolua_s, -2);     //获取第一个返回值
    string str = lua_tostring(tolua_s, -1);     //获取第二个返回值
    CCLOG("有参数和返回值的Lua函数的调用---%d---,%s",fValue,str.c_str());
    
    //--------------读取Lua的变量------------
    lua_getglobal(tolua_s, "strTemp");
    string strTemp = lua_tostring(tolua_s, -1);
     CCLOG("读取Lua的变量---%s",strTemp.c_str());
    
    //-------------读取Lua的table-----------
    lua_getglobal(tolua_s,"tableTemp");
    lua_getfield(tolua_s,-1,"name");
    string strName = lua_tostring(tolua_s,-1);
    CCLOG("读取Lua的table--%s",strName.c_str());


5.注意事项

1.如果你是cpp调用lua函数,那么你的这个lua函数不能是local的