Lua 'require' but files are only in memory

前端 未结 3 989
甜味超标
甜味超标 2021-02-14 16:59

Setting: I\'m using Lua from a C/C++ environment.

I have several lua files on disk. Those are read into memory and some more memory-only lua files become available duri

3条回答
  •  耶瑟儿~
    2021-02-14 17:39

    Instead of replacing require, why not add a function to package.loaders? The code is nearly the same.

    int my_loader(lua_State* state) {
        // get the module name
        const char* name = lua_tostring(state);
        // find if you have such module loaded
        if (mymodules.find(name) != mymodules.end())
        {
            luaL_loadbuffer(state, buffer, size, name);
            // the chunk is now at the top of the stack
            return 1;
        }
    
        // didn't find anything
        return 0;
    }
    
    // When you load the lua state, insert this into package.loaders
    

    http://www.lua.org/manual/5.1/manual.html#pdf-package.loaders

提交回复
热议问题