如何在cocos2d-x中将变量传递给Lua函数?

我正在尝试在cocos2d-x中调用lua函数。但是当我尝试传递一些变量给lua函数时,我的程序停在了lua_call()处。

我的函数:

const char* getData::callLuaFunction(const char* luaFileName,const char* functionName){
    lua_State*  ls = CCLuaEngine::defaultEngine()->getLuaStack()->getLuaState();

    std::string filefullpath = CCFileUtils::sharedFileUtils()->fullPathForFilename(luaFileName);
    const char* pfilefullpath = filefullpath.c_str();
    int isOpen = luaL_dofile(ls, pfilefullpath);
    if(isOpen!=0){
        CCLOG("Open Lua Error: %i", isOpen);
        return NULL;
    }

    lua_getglobal(ls, functionName);

    lua_pushstring(ls, "einverne");
    lua_pushnumber(ls, 2);
    lua_pushboolean(ls, true);

    lua_call(ls, 3, 1);
    const char* iResult = lua_tostring(ls, -1);
    return iResult;
}

lua文件中的函数:

function luaLogString(_logStr,_logNum,_logBool)
    print("Lua string from C:",_logStr,_logNum,_logBool)
    return "call lua function OK"
end

编辑:

我发现lua_call不是受保护的,lua_pcall函数更安全。当我改为lua_pcall时,错误显示为“尝试调用全局“聽聽聽聽print”(空值)”

点赞
用户1820217
用户1820217

实际上我找到了问题。

我删掉了 lua 文件中 print 函数之前的四个空格,一切正常了。

我建议新手使用 lua_pcall 而非 lua_call。因为如果在调用 lua_call 时出现错误,该函数将调用 exit(EXIT_FAILURE) 并关闭主机程序,而没有提供错误信息。

lua_pcalllua_call 之间的区别

2014-01-01 06:17:46