如何将Lua模块作为字符串而不是文件加载? [英] How Do I Load Lua Module as a String Instead of a File?
问题描述
我正在使用LuaJava和Lua的C代码.我想要做的是读取存储在Android应用程序中作为资源字符串的Lua源代码,以便可以执行Lua源代码读入.我需要知道如何使用LuaJava或C语言来做到这一点.
I am using LuaJava and C Code for Lua. What I am trying to do is read Lua source stored as a resource String in an Android application so that the Lua source read in can be executed. I need to know how to do this using LuaJava or C language.
我想知道如何使用字符串在Lua中创建Lua模块.
I want to know how I can create a Lua module in Lua by using a String.
换句话说,我将Lua源存储在String中,而该源将存储在.lua文件中.然后,我想将此字符串的内容作为可用的模块加载到Lua中.
In other words, I am storing Lua source that would be stored in a .lua file in a String instead. I then want to load the contents of this string into Lua as an available module that can be called.
我看到有一个loadstring()
函数,但不确定如何为LuaJava或C调用该函数.
I see there is a loadstring()
function but not sure how this would be invoked for LuaJava or C.
我不希望Lua在文件系统中搜索此文件,我将找到该文件并将其转换为字符串.有了字符串后,我需要知道如何将文件内容的字符串副本作为可以调用的模块加载到Lua中.
I don't want Lua to search the file system for this file, I will find the file and convert it to a string. After I have the string, I need to know how to load the string copy of the file contents into Lua as a module that I can then call.
我还想知道在调用loadstring(s)
之后,该模块是否仍可用于后续函数调用而无需重新加载,请再次执行loadstring()
.
I also want to know if after calling loadstring(s)
if the module will remain available for subsequent function calls without having to reload do the loadstring()
again.
推荐答案
If you need to load/compile a string from LuaJava, you can use the function LuaState.LloadString(String source)
.
如果您不想多次从源代码中加载模块",则必须为其分配一个名称,并在表中保存一些标志.您甚至可以提供卸载",以便您可以再次从源代码加载模块.可以在Lua中重新实现它,如下所示:
If you do not want to load a "module" from source multiple times, you have to assign it a name and save some flag in a table. You can even provide "unloading" so that you could load a module from source again. It could be reimplemented in Lua as follows:
do
local loadedModules = {} -- local so it won't leak to _G
function loadModule(name, source)
if loadedModules[name] then return loadedModules[name] end
loadedModules[name] = assert(loadstring(source))() or true
end
function unloadModule(name)
loadedModules[name] = nil
end
end
这篇关于如何将Lua模块作为字符串而不是文件加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!