cocos2d-x-lua工程的lua脚本加密

2014/1/26 更新

最近又发现了一个很简单的方法,其实coco2dx已经给我们提供设置loader的方法。

注意:有个局限性,在非android平台下调用pEngine->executeScriptFile是不调用loader的,只有require这种才会调用loader。也就是说你直接executeScriptFile("main.lua")这个脚本不能加密,main.lua里面require的才能加密

 

步骤如下:

1、实现自己的loader(参考int cocos2dx_lua_loader(lua_State *L))

#define CODE_MASK 250

extern "C"
{
    int decode_lua_loader(lua_State *L)
    {
        std::string filename(luaL_checkstring(L, 1));
        size_t pos = filename.rfind(".lua");
        if (pos != std::string::npos)
        {
            filename = filename.substr(0, pos);
        }
        
        pos = filename.find_first_of(".");
        while (pos != std::string::npos)
        {
            filename.replace(pos, 1, "/");
            pos = filename.find_first_of(".");
        }
        filename.append(".lua");
        
        unsigned long codeBufferSize = 0;
        unsigned char* codeBuffer = CCFileUtils::sharedFileUtils()->getFileData(filename.c_str(), "rb", &codeBufferSize);
        
        //-------------decode here
        for(int i=0; i<codeBufferSize; i++)
        {
            codeBuffer[i] ^= CODE_MASK; //xor decode
        }
        //-------------

        if (codeBuffer)
        {
            if (luaL_loadbuffer(L, (char*)codeBuffer, codeBufferSize, filename.c_str()) != 0)
            {
                luaL_error(L, "error loading module %s from file %s :\n\t%s",
                    lua_tostring(L, 1), filename.c_str(), lua_tostring(L, -1));
            }
            delete []codeBuffer;
        }
        else
        {
            CCLog("can not get file data of %s", filename.c_str());
        }
        
        return 1;
    }
}

2、添加loader

CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);
pEngine->addLuaLoader(decode_lua_loader);//add this

 

我在win32上测试通过



http://www.cnblogs.com/mrblue/archive/2013/06/06/3122543.html

你可能感兴趣的:(cocos2d-x-lua工程的lua脚本加密)