Lua“需要",但文件仅在内存中 [英] Lua 'require' but files are only in memory
问题描述
设置:我正在C/C ++环境中使用Lua.
Setting: I'm using Lua from a C/C++ environment.
我在磁盘上有几个lua文件.这些将被读取到内存中,并且在运行时可以使用一些仅用于内存的lua文件.想想一个编辑器,带有其他未保存的 lua 文件.
I have several lua files on disk. Those are read into memory and some more memory-only lua files become available during runtime. Think e.g. of an editor, with additional unsaved lua files.
因此,我在内存中有一个 list<标识符lua_file_content>
.其中一些文件中包含 require
语句.当我尝试将所有这些文件加载到lua实例(当前通过 lua_dostring
)时,我会尝试尝试调用全局需求(nil值).
So, I have a list<identifier, lua_file_content>
in memory. Some of these files have require
statements in them. When I try to load all these files to a lua instance (currently via lua_dostring
) I get attempt to call global require (a nil value)
.
是否有可能提供一个 require
函数,该函数可以代替旧的函数,而仅使用内存文件中提供的函数(那些文件在C端)?
Is there a possibility to provide a require
function, which replaces the old one and just uses the provided in memory files (those files are on the C side)?
是否有另一种方法允许这些文件中的 require
而不在磁盘上存储必需的文件?
Is there another way of allowing require
in these files without having the required files on disk?
一个示例是仅从内存中加载lua stdlib而不进行更改.(这实际上是我的测试用例.)
An example would be to load the lua stdlib from memory only without altering it. (This is actually my test case.)
推荐答案
为什么不替换 require
,而不是向 package.loaders
添加函数?代码几乎相同.
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
这篇关于Lua“需要",但文件仅在内存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!