Lua 'require' but files are only in memory

前端 未结 3 853
甜味超标
甜味超标 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:24

    A pretty straightforward C++ function that would mimic require could be: (pseudocode)

    int my_require(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
        lua_call(state)
        return 1;
    }
    

    Expose this function to Lua as require and you're good to go.

    I'd also like to add that to completely mimic require's behaviour, you'd probably need to take care of package.loaded, to avoid the code to be loaded twice.

提交回复
热议问题