如何将 Lua 模块作为字符串而不是文件加载? [英] How Do I Load Lua Module as a String Instead of a File?

查看:25
本文介绍了如何将 Lua 模块作为字符串而不是文件加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 Lua 使用 LuaJava 和 C 代码.我想要做的是读取作为资源字符串存储在 Android 应用程序中的 Lua 源,以便可以执行读入的 Lua 源.我需要知道如何使用 LuaJava 或 C 语言来做到这一点.

我想知道如何使用字符串在 Lua 中创建 Lua 模块.

换句话说,我正在存储 Lua 源代码,该源代码将存储在 .lua 文件中的字符串中.然后我想把这个字符串的内容作为一个可以调用的可用模块加载到 Lua 中.

我看到有一个 loadstring() 函数,但不确定如何为 LuaJava 或 C 调用它.

我不想让 Lua 在文件系统中搜索这个文件,我会找到这个文件并将其转换为字符串.获得字符串后,我需要知道如何将文件内容的字符串副本作为模块加载到 Lua 中,然后我可以调用该模块.

我还想知道在调用 loadstring(s) 之后模块是否仍可用于后续函数调用,而无需重新加载再次执行 loadstring().

解决方案

如果你需要从 LuaJava 加载/编译一个字符串,你可以使用函数 LuaState.LloadString(String source).>

如果您不想从源多次加载模块",则必须为其分配一个名称并在表中保存一些标志.您甚至可以提供卸载"功能,以便您可以再次从源代码加载模块.它可以在 Lua 中重新实现,如下所示:

做本地加载模块 = {} -- 本地所以它不会泄漏到 _G功能加载模块(名称,来源)如果loadedModules[name] 则返回loadedModules[name] endLoadedModules[name] = assert(loadstring(source))() 或 true结尾函数卸载模块(名称)LoadedModules[name] = nil结尾结尾

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.

I want to know how I can create a Lua module in Lua by using a String.

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.

I see there is a loadstring() function but not sure how this would be invoked for LuaJava or C.

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.

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).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆