3
votes

I am trying to call lua functions in cocos2d-x. However when I try to pass some variables to lua functions. My program stopped at lua_call().

My function:

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;
}

Function in lua file:

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

Edit: I have found lua_call is not protected. lua_pcall function is safer. And after I changed to lua_pcall. Errors show that attempt to call global '聽聽聽聽print' (a nil value)

1
Is there an error being emitted? - 0x499602D2
@0x499602D2 I cannot find a error, it just stopped. - einverne
Something wrong with lua_atpanic - einverne

1 Answers

3
votes

Actually I found the problem.

I delete four space before print function in lua file and everything is OK.

And I suggest newbie to use lua_pcall rather than lua_call. Because if there is an error when calling lua_call , this function will call exit(EXIT_FAILURE) and shutdown host program without giving an error message.

The difference between lua_pcall and lua_call