设置:我在C/C++环境中使用Lua.
我在磁盘上有几个lua文件.这些被读入内存,并且在运行时期间可以使用一些仅有内存的lua文件.想想一个编辑器,以及其他未保存的lua文件.
所以,我有一个list<identifier, lua_file_content>记忆.其中一些文件中包含require语句.当我尝试将所有这些文件加载到lua实例(当前通过lua_dostring)时,我得到了attempt to call global require (a nil value).
是否有可能提供一个require函数,它替换旧的函数,只使用提供的内存文件(这些文件在C端)?
是否有另一种允许require在这些文件中没有磁盘上所需文件的方法?
一个例子是只从内存加载lua stdlib而不改变它.(这实际上是我的测试用例.)
而不是替换require,为什么不添加一个功能package.loaders?代码几乎相同.
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
Run Code Online (Sandbox Code Playgroud)
http://www.lua.org/manual/5.1/manual.html#pdf-package.loaders
一个非常简单的C++函数可以模仿require:(伪代码)
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;
}
Run Code Online (Sandbox Code Playgroud)
把这个功能暴露给Lua require,你很高兴.
我还想补充一点来完全模仿require的行为,你可能需要注意package.loaded,以避免代码被加载两次.