Cocos2d-x3.0下 Lua与C++相互调用(二)

2014-11-24 13:01:39 · 作者: · 浏览: 1
g value = lua_tostring(ls, -1); result = result + key + : + value + ; lua_pop(ls, 1); } lua_pop(ls, 1); return result.c_str(); } const char* DJLCData::callLuaFunction(const char *luaFileName, const char *functionName) { lua_State* ls = LuaEngine::getInstance()->getLuaStack()->getLuaState(); int isOpen = luaL_dofile(ls, getFileFullPath(luaFileName)); if (isOpen) { log(Open Lua Error:%i,isOpen); return nullptr; } lua_getglobal(ls, functionName); lua_pushstring(ls, shen); lua_pushnumber(ls, 23); lua_pushboolean(ls, true); /* lua_call 第一个参数:函数的参数个数 第二个参数:函数返回值个数 */ lua_call(ls, 3, 1); const char* iResult = lua_tostring(ls, -1); return iResult; } void DJLCData::callCppFunction(const char *luaFileName) { lua_State* ls = LuaEngine::getInstance()->getLuaStack()->getLuaState(); /* Lua调用的C++的函数必须是静态的 */ lua_register(ls, cppFunction, cppFunction); int isOpen = luaL_dofile(ls, getFileFullPath(luaFileName)); if (isOpen != 0) { log(Open Lua Error:%i,isOpen); return; } } int DJLCData::cppFunction(lua_State *ls) { int luaNum = (int)lua_tonumber(ls, 1); char* luaStr = (char*)lua_tostring(ls, 2); log(Lua调用cpp函数时传来的两个参数:%i,%s,luaNum,luaStr); /* 返给Lua的值 */ lua_pushnumber(ls, 321); lua_pushstring(ls, shenqi); /* 返给Lua值个数 */ return 2; } const char* DJLCData::getFileFullPath(const char *fileName) { //src// 这里的//是指我的lua文件放在src这个目录下 std::string str = StringUtils::format(src//%s,fileName); return FileUtils::getInstance()->fullPathForFilename(str).c_str(); }

hello2.lua


function myadd(x, y)
    return x + y
end

luaStr = shenqi

luaTable = {name = xiaonan,age = 20}

function luaLogString(_logStr,_logNum,_logBool)

    print(Lua 脚本打印从C传来的字符串:,_logStr,_logNum,_logBool)
    return Call Lua function OK
end

function call_cpp(_logStr,_logNum,_logBool)
    num,str = cppFunction(999,lua string)
    print(从cpp函数中获得两个返回值:,num,str)
end


调用方法:

 log(%s,DJLCData::getInstance()->getLuaVarString(hello2.lua, luaStr));
        log(%s,DJLCData::getInstance()->getLuaVarOneOfTable(hello2.lua, luaTable, name));
        
        log(Table = %s,DJLCData::getInstance()->getLuaVarTable(hello2.lua, luaTable));
        
        log(Call Lua Function Back :%s,DJLCData::getInstance()->callLuaFunction(hello2.lua, luaLogString));
        
        DJLCData::getInstance()->callCppFunction(hello2.lua);
        DJLCData::getInstance()->callLuaFunction(hello2.lua, call_cpp);

cocos2d: shenqi
cocos2d: xiaonan
cocos2d: Table = name:xiaonan	age:20	
cocos2d: [LUA-print] Lua 脚本打印从C传来的字符串:	shen	23	true
cocos2d: Call Lua Function Back :Call Lua function OK
cocos2d: Lua调用cpp函数时传来的两个参数:999,lua string
cocos2d: [LUA-print] 从cpp函数中获得两个返回值:	321	shenqi