首页 文章

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

提问于
浏览
2

我试图在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 之后 . 错误显示 attempt to call global '聽聽聽聽print' (a nil value)

1 回答

  • 2

    其实我发现了这个问题 .

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

    我建议新手使用 lua_pcall 而不是 lua_call . 因为如果在调用 lua_call 时出错,则此函数将调用 exit(EXIT_FAILURE) 并关闭主机程序而不会显示错误消息 .

    lua_pcalllua_call 之间的区别

相关问题